替换评估者包含替换组后的编号

时间:2017-02-06 10:01:58

标签: c# regex

我想动态调整我的替换模式和评估者:

string pattern = "np";
string replacement = "ab";
string retval = Regex.Replace("Input", @"(.*)" + pattern + @"(.*)", @"$1" + replacement + @"$2";
// retval = "Iabut" => correct
string replacement = "12";
retval = Regex.Replace("Input", @"(.*)" + pattern + @"(.*)", @"$1" + replacement + @"$2";
// retval = "$112ut" => wrong

问题在于,在第二种情况下,我的评估者是"$112$2"所以我的第一个替换组将是$112

是否可以直接避免此类问题,还是需要在我的组定义和字符串之间添加分隔符?

1 个答案:

答案 0 :(得分:1)

作为替换参数,请使用

"${1}" + replacement.Replace("$", "$$") + "$2"

${1}中的大括号将确保引用第一个组,如果替换内部有.Replace("$", "$$")$将使其正常工作。

相关问题