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

How to Match Whole Words Only Using Regex in C#?

Mary-Kate Olsen
Release: 2025-01-22 19:56:11
Original
796 people have browsed it

How to Match Whole Words Only Using Regex in C#?

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

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

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!

source:php.cn
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