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方法旨在用于转义 Regex 模式,而不是替换,因为它可以转义其他字符,如斜杠和其他 Regex 模式字符。对我的问题的明显解决方法是让我的替换等于"$$1",并且将实现"Hello $1!",但我想知道美元符号是否是我必须逃避的唯一值(假设replacement是用户生成的,我不知道提前) ,或者是否已经有一个辅助函数可以做到这一点。
有谁知道一个函数来逃避Regex.Replace(string input, string pattern, string replacement)使用的替换值?