Home >Backend Development >C++ >How to Match Entire Words Only Using Regular Expressions in C#?

How to Match Entire Words Only Using Regular Expressions in C#?

Linda Hamilton
Linda HamiltonOriginal
2025-01-22 19:51:16548browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn