C# 如何在.NET Regex Replace中退出替换/替换部分
我想在.NET中的regex replace命令中转义替换部分:C# 如何在.NET Regex Replace中退出替换/替换部分,c#,.net,regex,replace,substitution,C#,.net,Regex,Replace,Substitution,我想在.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);
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)
我想确保价格是逐字替换的。Regex.Escape不起作用。您只需要在替换中转义$,因为所有替换都以$开头。即仅使用:
price.Replace("$", "$$");
有关详细信息,请参见以下问题:
替换是替换模式中唯一可识别的正则表达式语言元素。所有其他正则表达式语言元素,包括字符转义,仅在正则表达式模式中允许,在替换模式中不能识别
[……]
在替换模式中,$表示替换的开始
您只需要在替换中转义$,因为所有替换都以$开头。即仅使用:
price.Replace("$", "$$");
有关详细信息,请参见以下问题:
替换是替换模式中唯一可识别的正则表达式语言元素。所有其他正则表达式语言元素,包括字符转义,仅在正则表达式模式中允许,在替换模式中不能识别
[……]
在替换模式中,$表示替换的开始
或者只需更改字符串价格=$15/件;字符串价格=$$15/件;或者只需更改字符串价格=$15/件;字符串价格=$$15/件;