【问题标题】:How to escape the substitution/replacement part in .NET Regex Replace如何在 .NET Regex Replace 中转义替换/替换部分
【发布时间】:2014-01-08 20:52:54
【问题描述】:

我想在 .NET 中转义正则表达式替换命令中的替换部分:

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 不起作用。

【问题讨论】:

    标签: c# .net regex replace substitution


    【解决方案1】:

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

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

    详情请看以下问题:Handling regex escape replacement text that contains the dollar character

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

    [...]

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

    【讨论】:

    • 或者把string price = "$15/item" ;改成string price = "$$15/item" ;
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-04-17
    • 1970-01-01
    • 2016-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多