【问题标题】:Regex to match specific word [duplicate]正则表达式匹配特定单词[重复]
【发布时间】:2019-09-29 00:16:21
【问题描述】:

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();

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

请指教。谢谢!

【问题讨论】:

  • 试试'Key: ?Apple\b

标签: c# asp.net regex


【解决方案1】:

将您的模式替换为:

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

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

您可以阅读更多关于它的信息here.

【讨论】:

  • 您可以通过在Key 之后使用? 选择空格来进一步简化此模式:string pattern = @"('Key: ?Apple\b)"
  • 好点@derpirscher!
  • 谢谢!!问题已解决!
  • 祝你的项目好运!
猜你喜欢
  • 1970-01-01
  • 2014-06-01
  • 2013-06-10
  • 2018-01-02
  • 2016-03-17
  • 1970-01-01
  • 1970-01-01
  • 2017-04-28
  • 1970-01-01
相关资源
最近更新 更多