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

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

DDD
DDDOriginal
2025-01-22 20:09:09821browse

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

Match whole words using regular expression in C#

When using regular expressions to find matches in a string, it is crucial to ensure that only whole words are matched. Consider the task of matching specific words such as "shoes", "shirt", and "pants" in a content string.

Initially, one might think that the following regular expression will suffice:

<code>Regex.Match(content, keywords + "\s+", RegexOptions.Singleline | RegexOptions.IgnoreCase)</code>

However, this regex matches words like "participants" that contain the desired word "pants" but are not complete words themselves.

Solution: Word Boundaries

To solve this problem, word boundary characters (b) must be included in the regular expression. Word boundaries are invisible characters that mark the beginning and end of a word. By using word boundaries, the regex now only matches complete words:

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

New regular expression string search for any word that starts and ends with a word boundary. This ensures that only exact matches of the specified words are found. An additional "@" character at the beginning of a string indicates that the string should be treated as a verbatim string, preventing special characters from being interpreted as metacharacters.

The above is the detailed content of How to Match Whole 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