Use regular expression to match complete words in C#
In programming, it is often necessary to extract specific words from a string. In C#, regular expressions (Regex) provide a powerful tool for such tasks. However, matching whole words can be tricky if you don't think about it.
Consider the following scenario: You have a clothing store website and you want to match words related to clothing, such as "shoes", "shirt" or "pants". You wrote a regular expression:
<code>string keywords = "(shoes|shirt|pants)";</code>
And try to find these words in the content string using the following code:
<code>Regex.Match(content, keywords + "\s+", RegexOptions.Singleline | RegexOptions.IgnoreCase).Success</code>
However, this regex incorrectly matches "participants" because it contains "pants" as a substring. To match only exact words, be sure to use word separators, represented by \b
.
The modified regular expression becomes:
<code>\b(shoes|shirt|pants)\b</code>
By adding word separators, the regex now expects matched words to be preceded and followed by spaces, punctuation, or the beginning/end of a string. In code, this modified expression would be:
<code>Regex.Match(content, @"\b(shoes|shirt|pants)\b");</code>
With this modification, the regex will only match the literal words "shoes", "shirt" and "pants" in the content string.
The above is the detailed content of How Can I Use Regex in C# to Match Whole Words Only?. For more information, please follow other related articles on the PHP Chinese website!