c# - 具有特定字边界的正则表达式

标签 c# regex word-boundary

假设我有一个类型的字符串

(Price+Discounted_Price)*2-Max.Price

以及一个包含每个元素要替换的内容的字典

Price: A1 Discounted_Price: A2 Max.Price:A3

我怎样才能准确地替换每个短语,而不触及其他短语。这意味着搜索 Price 不应修改 Discounted_Price 中的 Price。结果应该是 (A1+A2)*2-A3 而不是 (A1+Discounted_A1) - Max.A1 或其他任何内容

谢谢。

最佳答案

如果您的变量可以由字母数字/下划线/点字符组成,您可以将它们与 [\w.]+ 匹配。正则表达式模式,并添加包含 . 的边界:

using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
public class Test
{
    public static void Main()
    {
        var s = "(Price+Discounted_Price)*2-Max.Price";
        var dct = new Dictionary<string, string>();
        dct.Add("Price", "A1");
        dct.Add("Discounted_Price", "A2");
        dct.Add("Max.Price","A3");
        var res = Regex.Replace(s, @"(?<![\w.])[\w.]+(?![\w.])",     // Find all matches with the regex inside s
            x => dct.ContainsKey(x.Value) ?   // Does the dictionary contain the key that equals the matched text?
                  dct[x.Value] :              // Use the value for the key if it is present to replace current match
                  x.Value);                   // Otherwise, insert the match found back into the result
        Console.WriteLine(res);
    }
}

请参阅IDEONE demo

(?<![\w.])如果匹配前面有单词或点字符,并且 (?![\w.]) ,则负后向查找会失败。如果负向先行后跟单词或点字符,则匹配失败。

请注意[\w.]+允许在前导和尾随位置有一个点,因此,您可能需要将其替换为 \w+(?:\.\w+)*并用作@"(?<![\w.])\w+(?:\.\w+)*(?![\w.])" .

更新

由于您已经提取了要替换的关键字作为列表,因此您需要使用更复杂的单词边界(不包括点):

var listAbove = new List<string> { "Price", "Discounted_Price", "Max.Price" };
var result = s;
foreach (string phrase in listAbove)
{
    result = Regex.Replace(result, @"\b(?<![\w.])" + Regex.Escape(phrase) +  @"\b(?![\w.])", dct[phrase]);
}

参见IDEONE demo .

关于c# - 具有特定字边界的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37468103/

相关文章:

java - 我如何在Java中验证日期(仅当前日期或之后)

Elasticsearch 标准分词器行为和单词边界

c# - 需要确定屏幕分辨率以在 ASP.NET 网页上显示必要的项目

C# 如何模拟 Configuration.GetSection ("foo:bar").Get<List<string>>()

c++ - 以数字结尾的字符串的正则表达式

javascript - 匹配包含单词的整个句子,即使句子跨越多行

C# 数据读取器 : Sql Batch Of Commands And Return Results

c# - 如何使用日期范围获取目录中的文件?

java - 拒绝前导/结尾非字母数字字符的字边界

javascript - 使用 jQuery (Javascript) 在段落中查找 "word"索引