我有一个搜索词的列表,我希望有一个正则表达式,以匹配所有的项目,其中至少有两个。
条款:战争,军队,战斗,叛军,冲突
匹配:在反叛者和之间发生了几次冲突。(4次点击)
非匹配:在反恐战争中,奥巴马政府希望增加无人机袭击的数量。(只命中一次)
背景:我使用微型rss收集和过滤一个新闻报道项目的大量提要。我每天得到1000-2000个饲料项目,并希望通过关键字过滤它们。通过使用\\或表达式,我得到了许多假阳性,所以我想我只需要在一个提要项目中要求两次匹配。
谢谢!
编辑:
我对regex知之甚少,所以到目前为止,我一直在使用简单的x或运算符。我试着把搜索词放在括号中(war\fighting\等){2,},但是只有当一个项目两次使用相同的单词时,它才匹配。
EDIT2:对不起,我对regex和诸如此类的东西不太熟悉。事实是: regex查询mysql数据库。它作为过滤器输入到tt-rss后端,它只允许一行(尽管理论上不允许字符数量)。过滤器是在将提要项导入mysql数据库时使用的。
发布于 2012-05-31 11:20:22
(.*?\b(war|army|fighting|rebels|clashes)\b){2,}如果需要避免匹配同一术语,可以使用:
.*?\b(war|army|fighting|rebels|clashes).*?(\b(?!\1)(war|army|fighting|rebels|clashes)\b)它与一个术语匹配,但通过使用负前瞻性避免了再次匹配相同的术语。
在java中:
Pattern multiword = Pattern.compile(
".*?(\\b(war|army|fighting|rebels|clashes)\\b)" +
".*?(\\b(?!\\1)(war|army|fighting|rebels|clashes)\\b)"
);
Matcher m;
for(String str : Arrays.asList(
"war",
"war war war",
"warm farmy people",
"In the war on terror rebels eating faces"
)) {
m = multiword.matcher(str);
if(m.find()) {
logger.info(str + " : " + m.group(0));
} else {
logger.info(str + " : no match.");
}
}指纹:
war : no match.
war war war : no match.
warm farmy people : no match.
In the war on terror rebels eating faces : In the war on terror rebels发布于 2012-05-31 11:24:41
这(完全)并不是正则表达式的工作。更好的方法是扫描文本,然后计数唯一的匹配组。
在Ruby中,基于匹配计数的分支非常简单。例如:
terms = /war|army|fighting|rebels|clashes/
text = "The war between the rebels and the army resulted in..."
# The real magic happens here.
match = text.scan(terms).uniq
# Do something if your minimum match count is met.
if match.count >= 2
p match
end这将打印["war", "rebels", "army"]。
发布于 2012-05-31 11:21:31
正则表达式可以做到这一点,但正则表达式将是相当庞大的。
记住,它们是简单的工具(基于有限状态自动机),因此没有任何记忆让他们记住已经看到的单词。因此,这样的正则表达式,即使是可能的,也可能只是看起来像一个巨大的块(如“1”或“对于每个可能的输入顺序或其他东西)。
我建议自己进行解析,例如:
var searchTerms = set(yourWords);
int found = 0;
foreach (var x in words(input)) {
if (x in searchTerms) {
searchTerms.remove(x);
++found;
}
if (found >= 2) return true;
}
return false;https://stackoverflow.com/questions/10832519
复制相似问题