Regex.Match whole words

后端 未结 4 1507
暖寄归人
暖寄归人 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: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.

提交回复
热议问题