正则表达式匹配整个单词 [英] Regex.Match whole words

查看:1478
本文介绍了正则表达式匹配整个单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C#中,我想使用正则表达式来匹配以下任何一个单词:

In C#, I want to use a regular expression to match any of these words:

string keywords = "(shoes|shirt|pants)";

我想在内容字符串中找到整个单词。我以为这个 regex 可以做到这一点:

I want to find the whole words in the content string. I thought this regex would do that:

if (Regex.Match(content, keywords + "\\s+", 
  RegexOptions.Singleline | RegexOptions.IgnoreCase).Success)
{
    //matched
}

,但对于像参与者这样的单词,它返回true想要整个单词 pants

but it returns true for words like participants, even though I only want the whole word pants.

我怎么只匹配那些文字呢?

How do I match only those literal words?

推荐答案

您应该在正则表达式中添加定界符:

You should add the word delimiter to your regex:

\b(shoes|shirt|pants)\b

在代码中:

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

这篇关于正则表达式匹配整个单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆