Home >Backend Development >C++ >How Can I Match Whole Words Only Using Regular Expressions in C#?
In C#, regular expressions are often used to find specific patterns in text. However, when trying to match complete words, care needs to be taken to avoid matching partial words.
Suppose you need to find the words "shoes", "shirt" or "pants" in a text:
<code>string keywords = "(shoes|shirt|pants)";</code>
It seems easy to use the Regex.Match
method:
<code>if (Regex.Match(content, keywords + "\s+", RegexOptions.Singleline | RegexOptions.IgnoreCase).Success) { //匹配 }</code>
However, this expression will also match words like "participants" because it treats "pants" as a partial match within a larger word. To solve this problem, we need to match complete words explicitly.
Word boundaries in regular expressions are represented by the b
characters. By adding word boundaries to the regular expression, you can ensure that only exact matching words are recognized:
<code>Regex.Match(content, @"\b(shoes|shirt|pants)\b");</code>
Here is the updated code to correctly match words based on your criteria:
<code>string keywords = "(shoes|shirt|pants)"; if (Regex.Match(content, @"\b(shoes|shirt|pants)\b").Success) { //匹配 }</code>
With this modification, only the three complete words "shoes", "shirt" and "pants" will be considered as matches, ensuring the accuracy of the matching operation.
The above is the detailed content of How Can I Match Whole Words Only Using Regular Expressions in C#?. For more information, please follow other related articles on the PHP Chinese website!