正则表达式匹配多个字符串 [英] Regex to match multiple strings
问题描述
我需要创建一个正则表达式可以匹配多个字符串。例如,我想找到一个好或伟大的所有实例。我发现了一些例子,但似乎我想出了不工作:
I need to create a regex that can match multiple strings. For example, I want to find all the instances of "good" or "great". I found some examples, but what I came up with doesn't seem to work:
\b(good|great)\w*\b
任何人都可以点我在正确的方向?
Can anyone point me in the right direction?
编辑:我要指出,我不希望只是全字匹配。例如,我可能要匹配OOD或不动产资产信托,以及(的词的部分)。
I should note that I don't want to just match whole words. For example, I may want to match "ood" or "reat" as well (parts of the words).
编辑2:下面是一些示例文本:这是一个真正伟大的故事。的
我可能要匹配这个或真正的,或者我可能要匹配eall或不动产资产信托。
Edit 2: Here is some sample text: "This is a really great story." I might want to match "this" or "really", or I might want to match "eall" or "reat".
推荐答案
如果你能保证有你的话清单中没有保留正则表达式的字符(或者,如果你逃避他们),你可以只使用这code到让大的单词列表
到 @(A |大|字|列表)
。没有什么错的 |为你使用它
运营商,只要那些()
围绕着它。这听起来像 \\ W *
和 \\ b
模式是什么干扰你的比赛。
If you can guarantee that there are no reserved regex characters in your word list (or if you escape them), you could just use this code to make a big word list
into @"(a|big|word|list)"
. There's nothing wrong with the |
operator as you're using it, as long as those ()
surround it. It sounds like the \w*
and the \b
patterns are what are interfering with your matches.
String[] pattern_list = whatever;
String regex = String.Format("({0})", String.Join("|", pattern_list));
这篇关于正则表达式匹配多个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!