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
Release: 2025-01-22 19:51:16
Original
618 people have browsed it

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>
Copy after login

In C# code:

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

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 of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template