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
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With