6
votes

Regex.Replace says :

In a specified input string, replaces all strings that match a specified regular expression with a specified replacement string.

In my case:

string w_name = "0x010102_default_prg_L2_E2_LDep1_LLC";
string regex_exp = @"(?:E\d)([\w\d_]+)(?:_LLC)";
w_name = Regex.Replace(w_name, regex_exp, string.Empty);

Output:

0x010102_default_prg_L2_

but I was expecting

0x010102_default_prg_L2_E2_LLC

Why is it replacing my non-matching groups(group 1 and 3)? And how do I fix this in order to get the expected output?

Demo

1

1 Answers

5
votes

Turn the first and last non-capturing groups to capturing groups so that you could refer thoses chars in the replacement part and remove the unnecessary second capturing group.

string w_name = "0x010102_default_prg_L2_E2_LDep1_LLC";
string regex_exp = @"(E\d)[\w\d_]+(_LLC)";
w_name = Regex.Replace(w_name, regex_exp, "$1$2");

DEMO

or

string regex_exp = @"(?<=E\d)[\w\d_]+(?=_LLC)";
w_name = Regex.Replace(w_name, regex_exp, string.Empty);