Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/298.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何在.NET Regex Replace中退出替换/替换部分_C#_.net_Regex_Replace_Substitution - Fatal编程技术网

C# 如何在.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);

我想在.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)
我想确保价格是逐字替换的。Regex.Escape不起作用。

您只需要在替换中转义$,因为所有替换都以$开头。即仅使用:

price.Replace("$", "$$");
有关详细信息,请参见以下问题:

替换是替换模式中唯一可识别的正则表达式语言元素。所有其他正则表达式语言元素,包括字符转义,仅在正则表达式模式中允许,在替换模式中不能识别

[……]

在替换模式中,$表示替换的开始

您只需要在替换中转义$,因为所有替换都以$开头。即仅使用:

price.Replace("$", "$$");
有关详细信息,请参见以下问题:

替换是替换模式中唯一可识别的正则表达式语言元素。所有其他正则表达式语言元素,包括字符转义,仅在正则表达式模式中允许,在替换模式中不能识别

[……]

在替换模式中,$表示替换的开始

或者只需更改字符串价格=$15/件;字符串价格=$$15/件;或者只需更改字符串价格=$15/件;字符串价格=$$15/件;