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

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

Barbara Streisand
Release: 2025-01-22 20:17:12
Original
308 people have browsed it

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

Exactly match complete words using C# regular expressions

In C#, regular expressions are often used to find specific patterns in text. However, when trying to match complete words, care needs to be taken to avoid matching partial words.

Suppose you need to find the words "shoes", "shirt" or "pants" in a text:

<code>string keywords = "(shoes|shirt|pants)";</code>
Copy after login

It seems easy to use the Regex.Match method:

<code>if (Regex.Match(content, keywords + "\s+", 
  RegexOptions.Singleline | RegexOptions.IgnoreCase).Success)
{
    //匹配
}</code>
Copy after login

However, this expression will also match words like "participants" because it treats "pants" as a partial match within a larger word. To solve this problem, we need to match complete words explicitly.

Solution: Use word boundaries

Word boundaries in regular expressions are represented by the b characters. By adding word boundaries to the regular expression, you can ensure that only exact matching words are recognized:

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

Updated code

Here is the updated code to correctly match words based on your criteria:

<code>string keywords = "(shoes|shirt|pants)";
if (Regex.Match(content, @"\b(shoes|shirt|pants)\b").Success)
{
    //匹配
}</code>
Copy after login

With this modification, only the three complete words "shoes", "shirt" and "pants" will be considered as matches, ensuring the accuracy of the matching operation.

The above is the detailed content of How Can I Match Whole Words Only Using Regular Expressions 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