正则表达式匹配相同的单词

时间:2019-01-04 16:24:57

标签: php regex

假设是随机单词(前提是两个相同),仅在此处表示:

我正在尝试使用正则表达式在任何地方匹配 YES OR YES ,条件是 只有在字符串为2的情况下,字符串才必须匹配。

因此,如果我尝试使用以下测试字符串:

yes or yes
no or yes
yes or no
maybe yes or yes
maybe yes or no
yes maybe or yes
maybe yes maybe yes maybe or

它只能匹配以下内容:

yes or yes
maybe yes or yes
yes maybe or yes
maybe yes maybe yes maybe or

这是我正在处理的正则表达式查询:

^(?=.*(?=\w.*yes)(?=\w.*or)(?=\w.*yes)).*

很遗憾,我的查询仍然与no or yes相匹配。 这是我的正则表达式链接:Click Here

2 个答案:

答案 0 :(得分:0)

为什么不呢?

^(?=.*\byes\b.+\byes\b)(?=.*\bor\b).+

第一个正向前行查找两个yes,第二个正则匹配or

demo on regex101

答案 1 :(得分:0)

使用substr_count()

非正则表达式
<?php
$string = 'yes or yes
no or yes
yes or no
maybe yes or yes
maybe yes or no
yes maybe or yes
maybe yes maybe yes maybe or';
$array =   explode("\n", $string);
$expected = [];
//print_r($array);
foreach($array as $line){
    $words = substr_count($line,'yes');
    if($words==2 && strpos($line, 'or') !== false ){
     $expected[]= $line;   
    }
}

echo implode("\n",$expected);

输出:

yes or yes
maybe yes or yes
yes maybe or yes
maybe yes maybe yes maybe or

演示: https://3v4l.org/uL7fJ