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
  • 561,645
  • 34
  • 376
  • 476
jhonny625
  • 266
  • 2
  • 14

2 Answers2

6

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
  • 561,645
  • 34
  • 376
  • 476
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