使用正则表达式以任何顺序匹配多个单词 [英] match multiple words in any order with regex

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

问题描述

好吧,假设我想在一个句子中匹配 3 个单词...但我需要以任何顺序匹配它们,例如:

Ok lets say I whant to match 3 words in a sentence... but I neet to match them in any order, for example:

$sentences = Array(
   "one two three four five six seven eight nine ten",
   "ten nine eight seven six five four three two one",
   "one three five seven nine ten",
   "two four six eight ten",
   "two ten four six one",
);

所以我需要匹配单词二"、四"&十",但以任何顺序排列,它们之间可以或不可以有任何其他词.我试试

So I need to match the words "two", "four" & "ten", but in any order and they can or not have any other words between them. I Try

foreach($sentences AS $sentence) {
   $n++;
   if(preg_match("/(two)(.*)(four)(.*)(ten)/",$sentence)) {
       echo $n." matched\n";
   }
}

但这只会匹配句子 1,我需要匹配句子 1,2,4 &5.

But this will match ONLY sentence 1 and I need to match in sentence 1,2,4 & 5.

希望能帮到你...问候!(对不起我的英语)

I hope you can help... Regards! (and sorry for my english)

推荐答案

您可以使用 Positive Lookahead 来实现这一点.

You could use Positive Lookahead to achieve this.

先行方法非常适合匹配包含这些子字符串的字符串,而不管顺序.

The lookahead approach is nice for matching strings that contain these substrings regardless of order.

if (preg_match('/(?=.*two)(?=.*four)(?=.*ten)/', $sentence)) {
    echo $n." matched\n";
}

代码演示

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

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