Regex.Match whole words

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

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

I want to find whole words in the content bar. I thought this regex would do this:

 if (Regex.Match(content, keywords + "\\s+", RegexOptions.Singleline | RegexOptions.IgnoreCase).Success) { //matched } 

but it returns true for words like participants , although I only need the word pants .

How do I match only these literal words?

+41
c # regex
Jul 30 '09 at 20:11
source share
4 answers

You should add a word delimiter to your regular expression:

 \b(shoes|shirt|pants)\b 

In code:

 Regex.Match(content, @"\b(shoes|shirt|pants)\b"); 
+73
Jul 30 '09 at 20:13
source share
— -

Try

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

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

+13
Jul 30 '09 at 20:17
source share

You need a statement with zero width on both sides, that the characters before or after the word are not part of the word:

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

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

+4
Jul 30 '09 at 20:14
source share

place the word boundary on it using the metabacteria \ b.

+1
Jul 30 '09 at 20:13
source share



All Articles