Home >Backend Development >C++ >How to Match Entire Words Only Using Regular Expressions in C#?
C# regular expression complete word matching
In C#, it is very common to use regular expressions to find specific words in a given string. However, ensuring that only whole words are matched can be challenging.
Question:
When trying to match words like "shoes", "shirt" or "pants" using the regex keyword s
it will inadvertently match words like "participants". This is because regular expressions lack a mechanism to differentiate between words and substrings.
Solution:
To solve this problem, word separators (b
) must be incorporated into the regular expression. Word separators mark the beginning and end of word boundaries, ensuring that a match only occurs when the target word is a complete word rather than a part of a larger term.
Code correction:
The updated regular expression containing word separators is:
<code>\b(shoes|shirt|pants)\b</code>
In C# code:
<code class="language-csharp">Regex.Match(content, @"\b(shoes|shirt|pants)\b");</code>
With this fixed regular expression, only words that exactly match "shoes", "shirt" or "pants" will be recognized, preventing false matches like "participants".
The above is the detailed content of How to Match Entire Words Only Using Regular Expressions in C#?. For more information, please follow other related articles on the PHP Chinese website!