[英]How to escape the substitution/replacement part in .NET Regex Replace
I want to escape the substitution part in a regex replace command in .NET: 我想在.NET中的regex replace命令中转义替换部分:
public static string GetPriceMessage(string data, string price)
{
var repl = "This is a $1 priced at " + price + " suitable for $2.";
return Regex.Replace(data, "item_name: ([^;]+); suitable: ([^;]+)", repl);
}
var price = "$15/item";
var data = "item_name: Puzzle; suitable: all ages";
GetPriceMessage(data, price)
I want to make sure price
is substituted verbatim. 我想确保
price
被逐字替换。 Regex.Escape
doesn't work. Regex.Escape
不起作用。
You only need to escape $
in substitutions, since all substitutions start with $
. 您只需在替换中转义
$
,因为所有替换均以$
开头。 Ie just use: 即只使用:
price.Replace("$", "$$");
See the following question for details: Handling regex escape replacement text that contains the dollar character 有关详细信息,请参见以下问题: 处理包含美元字符的正则表达式转义替换文本
Substitutions are the only regular expression language elements that are recognized in a replacement pattern.
替换是在替换模式中唯一可识别的正则表达式语言元素。 All other regular expression language elements, including character escapes, are allowed in regular expression patterns only and are not recognized in replacement patterns.
所有其他正则表达式语言元素(包括字符转义符)仅在正则表达式模式中允许使用,而在替换模式中不识别。
[...] [...]
In a replacement pattern, $ indicates the beginning of a substitution.
在替换模式中,$表示替换的开始。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.