7

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.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
jhonny625
  • 266
  • 2
  • 14

2 Answers2

8

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+)
   ^^^
Community
  • 1
  • 1
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • Using string interpolation can avoid changing index num for `string.Format()` But the drawback is you have to remember to un-escape `{{X}}` back to original valid regex value when you copy the regex string value to use at somewhere else – Grace Dec 08 '22 at 08:16
1

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);
  • I think the braces were meant to be part of the regex. Since actual braces have to be escaped for `String.Format()`, it should be `{{{0}}}`. – Alan Moore Jul 09 '16 at 08:31
  • Here all those thing is convert as string and where we had written " {0} " for passing parameter which replace with value of " i ". – Gautam Kumar Sahu Sep 20 '16 at 06:00