繁体   English   中英

如何在.NET Regex Replace中转义替换/替换部分

[英]How to escape the substitution/replacement part in .NET Regex Replace

我想在.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)

我想确保price被逐字替换。 Regex.Escape不起作用。

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

price.Replace("$", "$$");

有关详细信息,请参见以下问题: 处理包含美元字符的正则表达式转义替换文本

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

[...]

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM