Regex.Replace 说:
In a specified input string, replaces all strings that match a specified regular expression with a specified replacement string.
以我为例:
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);
输出:
0x010102_default_prg_L2_
但我很期待
0x010102_default_prg_L2_E2_LLC
为什么要替换我的不匹配组(第 1 组和第 3 组)?我该如何解决这个问题以获得预期的输出?
最佳答案
将第一个和最后一个非捕获组转换为捕获组,以便您可以在替换部分中引用这些字符并删除不必要的第二个捕获组。
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");
或
string regex_exp = @"(?<=E\d)[\w\d_]+(?=_LLC)";
w_name = Regex.Replace(w_name, regex_exp, string.Empty);
关于c# - 正则表达式只替换匹配的组并忽略不匹配的组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32073362/