正则表达式以匹配特定词

时间:2019-05-11 08:32:51

标签: c# asp.net regex

C#

        string myString = @"'Key:Apple
                            'Key:Apple123";
        string pattern = "('Key:Apple)|('Key: Apple)";
        int count = Regex.Matches(myString, pattern).Count;
        Console.WriteLine(count); //displaying count as 2
        Console.ReadLine();

我只搜索Apple(而不是Apple123),但仍然是2。我如何只搜索特定单词“ Apple”,然后显示为1?

我尝试了以下方法:

            string myString = @"'Key:Apple
                                'Key:Apple123";
            string pattern = "(\\b'Key:Apple\\b)|(\\b'Key: Apple\\b)";
            int count = Regex.Matches(myString, pattern).Count;
            Console.WriteLine(count); //displaying count as 0
            Console.ReadLine();

使用上述方法,我们将计数设为零。

请咨询。谢谢!

1 个答案:

答案 0 :(得分:0)

替换您的图案:

string pattern = @"(Key:\bApple\b)|(Key: \bApple\b)";

\b会检查单词边界,并能够在您的示例中将count评估为1。

您可以详细了解here.