Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex Pattern Matching Concatenation

Is it possible to concatenate the results of Regex Pattern Matching using only Regex syntax?

The specific instance is a program is allowing regex syntax to pull info from a file, but I would like it to pull from several portions and concatenate the results.

For instance:

Input string: 1234567890

Desired result string: 2389

Regex Pattern match: (?<=1).+(?=4)%%(?<=7).+(?=0)

Where %% represents some form of concatenation syntax. Using starting and ending with syntax is important since I know the field names but not the values of the field.

Does a keyword that functions like %% exist? Is there a more clever way to do this? Must the code be changed to allow multiple regex inputs, automatically concatenating?

Again, the pieces to be concatenated may be far apart with unknown characters in between. All that is known is the information surrounding the substrings.

2011-08-08 edit: The program is written in C#, but changing the code is a major undertaking compared to finding a regex-based solution.

like image 497
Noisedestroyers Avatar asked Aug 08 '11 12:08

Noisedestroyers


1 Answers

Without knowing exactly what you want to match and what language you're using, it's impossible to give you an exact answer. However, the usual way to approach something like this is to use grouping.

In C#:

string pattern = @"(?<=1)(.+)(?=4).+(?<=7)(.+)(?=0)";
Match m = Regex.Match(input, pattern);

string result = m.Groups[0] + m.Groups[1];

The same approach can be applied to many other languages as well.

Edit

If you are not able to change the code, then there's no way to accomplish what you want. The reason is that in C#, the regex string itself doesn't have any power over the output. To change the result, you'd have to either change the called method of the Regex class or do some additional work afterwards. As it is, the method called most likely just returns either a Match object or a list of matching objects, neither of which will do what you want, regardless of the input regex string.

like image 173
Brian Kintz Avatar answered Sep 28 '22 05:09

Brian Kintz