Regex replaces only the relevant groups and ignores inconsistent groups?

Regex.Replace says:

The specified input line replaces all lines matching the specified regular expression with the specified replacement.

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 inappropriate groups (groups 1 and 3)? And how do I fix this to get the expected result?

Demo

+5
source share
1 answer

Rotate the first and last non-capturing groups to capture the groups so that you can refer to the characters in the spare part and delete the unnecessary second capture 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); 
+5
source

All Articles