Only match the whole word in C# regular expression
Question:
In C#, how to construct a regular expression to match an entire word in a given keyword list? Specifically, given the following list of keywords:
<code>string keywords = "(shoes|shirt|pants)";</code>
We want to match these words in a text string, but discard partial matches such as "participants" if we are only interested in the exact word "pants".
Answer:
To ensure that the regular expression matches the entire word, we need to include word boundaries, represented by the b
symbol. b
represents the boundary between word and non-word characters.
The modified regular expression is as follows:
<code>\b(shoes|shirt|pants)\b</code>
When used as a condition in a Regex.Match
statement, this expression will only match whole words that exactly match any keyword in the given list.
The above is the detailed content of How to Match Whole Words Only Using Regex in C#?. For more information, please follow other related articles on the PHP Chinese website!