C#,Regex.Match整个单词 [英] C#, Regex.Match whole words

查看:213
本文介绍了C#,Regex.Match整个单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C#,我想用一个常规的前pression匹配任何字:

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

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

我想找到整个词语的内容字符串。我认为这正则表达式将做到这一点:

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

但像参加的话返回true,即使我只想要整个单词裤子

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

在code:

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

这篇关于C#,Regex.Match整个单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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