Regex.Match whole words

后端 未结 4 1428
暖寄归人
暖寄归人 2020-11-22 07:58

In C#, I want to use a regular expression to match any of these words:

string keywords = \"(shoes|shirt|pants)\";

I want to fi

相关标签:
4条回答
  • 2020-11-22 08:15

    You should add the word delimiter to your regex:

    \b(shoes|shirt|pants)\b
    

    In code:

    Regex.Match(content, @"\b(shoes|shirt|pants)\b");
    
    0 讨论(0)
  • 2020-11-22 08:25

    Try

    Regex.Match(content, @"\b" + keywords + @"\b", RegexOptions.Singleline | RegexOptions.IgnoreCase)
    

    \b matches on word boundaries. See here for more details.

    0 讨论(0)
  • 2020-11-22 08:29

    You need a zero-width assertion on either side that the characters before or after the word are not part of the word:

    (?=(\W|^))(shoes|shirt|pants)(?!(\W|$))
    

    As others suggested, I think \b will work instead of (?=(\W|^)) and (?!(\W|$)) even when the word is at the beginning or end of the input string, but I'm not sure.

    0 讨论(0)
  • 2020-11-22 08:31

    put a word boundary on it using the \b metasequence.

    0 讨论(0)
提交回复
热议问题