Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a dynamic value to quantifier in C# regex

Tags:

c#

regex

replace

I have a regex that I am trying to pass a variable to:

int i = 0;  
Match match = Regex.Match(strFile, "(^.{i})|(godness\\w+)(?<=\\2(\\d+).*?\\2)(\\d+)");

I'd like the regex engine to parse {i} as the number that the i variable holds.

The way I am doing that does not work as I get no matches when the text contains matching substrings.

like image 903
jhonny625 Avatar asked Jul 09 '16 04:07

jhonny625


2 Answers

It is not clear what strings you want to match with your regex, but if you need to use a vriable in the pattern, you can easily use string interpolation inside a verbatim string literal. Verbatim string literals are preferred when declaring regex patterns in order to avoid overescaping.

Since string interpolation was introduced in C#6.0 only, you can use string.Format:

string.Format(@"(^.{{{0}}})|(godness\w+)(?<=\2(\d+).*?\2)(\d+)", i)

Else, beginning with C#6.0, this seems a better alternative:

int i = 0;
Match match = Regex.Match(strFile, $@"(^.{{{i}}})|(godness\w+)(?<=\2(\d+).*?\2)(\d+)");

The regex pattern will look like

(^.{0})|(godness\w+)(?<=\2(\d+).*?\2)(\d+)
   ^^^
like image 146
Wiktor Stribiżew Avatar answered Oct 05 '22 22:10

Wiktor Stribiżew


You may try this Concept, where you may use i as parameter and put any value of i.

int i = 0;
 string Value =string.Format("(^.{0})|(godness\\w+)(?<=\\2(\\d+).*?\\2)(\\d+)",i);
 Match match = Regex.Match(strFile, Value);
like image 43
Gautam Kumar Sahu Avatar answered Oct 05 '22 23:10

Gautam Kumar Sahu