.NET Regex中带有字边界的正则表达式失败

时间:2015-04-27 08:14:45

标签: c# .net regex

我在C#中遇到.NET正则表达式问题。我们正在尝试匹配段落符号§所包围的文本中的特殊标记。为了完整起见,相应的正则表达式被单词边界\b包围。问题是由\b包围的正则表达式与单词:

不匹配
    static void Main(string[] args)
    {
        string data = "I would like to replace this §pattern§ with something interesting";
        string requiredResult = "I would like to replace this serious text with something interesting";

        Regex regSuccess = new Regex("§pattern§");
        Regex regFail = new Regex(@"\b§pattern§\b");

        var dataSuccess = regSuccess.Replace(data, "serious text");
        var dataFail = regFail.Replace(data, "serious text");

        Console.WriteLine("regSuccess match: {0}", dataSuccess == requiredResult);
        Console.WriteLine("regFail match: {0}", dataFail == requiredResult);
        Console.WriteLine("Press enter to continue");
        var line = Console.ReadLine();
    }

如您所见,dataFail == requiredResult会返回false

1 个答案:

答案 0 :(得分:4)

替换

Regex regFail = new Regex(@"\b§pattern§\b");

Regex regFail = new Regex(@"§\bpattern\b§");

§是一个非单词字符,因此\b会阻止pattern匹配。也许,你甚至不需要\b,因为pattern已经在非单词字符里面了?

Regex regFail = new Regex(@"§pattern§");