【发布时间】:2023-03-18 00:46:01
【问题描述】:
string input = "Hello World!";
string pattern = "(World|Universe)";
string replacement = "$1";
string result = Regex.Replace(input, pattern, replacement);
有以下示例,结果将是"Hello World!",因为$1 被第一组(World|Universe) 替换,但是我想要的结果是"Hello $1!"
Regex.Escape 方法旨在用于转义正则表达式模式,而不是替换,因为它可以转义其他字符,如斜杠和其他正则表达式模式字符。我的问题的明显解决方法是让我的替换等于"$$1",并将实现"Hello $1!",但我想知道美元符号是否是我必须逃避的唯一值(假设replacement是用户生成的,并且我不提前知道),或者是否有一个辅助函数已经这样做了。
有谁知道一个函数来逃避Regex.Replace(string input, string pattern, string replacement) 使用的替换值?
【问题讨论】: