"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Match Entire Words Only Using Regular Expressions in C#?

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

Posted on 2025-02-22
Browse:549

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

C# Regular Expression Complete Word Match

]

In C#, it is common to use regular expressions to find specific words in a given string. However, ensuring that only matches the entire word can be challenging.

question:

When trying to match words like "shoes", "shirt", or "pants" using the regular expression keyword \s , it inadvertently matches words like "participants". This is because regular expressions lack a mechanism to distinguish between words and substrings.

Solution:

To solve this problem, the word separator (\b) must be merged into the regular expression. The word separator marks the beginning and end of the word boundary, ensuring that matches occur only if the target word is a complete word rather than a part of a larger term.

Code Fix:

The updated regular expression containing word separators is:

\b(shoes|shirt|pants)\b
]

In C# code:

Regex.Match(content, @"\b(shoes|shirt|pants)\b");

Use this modified regular expression, only words that exactly match "shoes", "shirt", or "pants" will be recognized, thus preventing false matches such as "participants".

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3