正则表达式以任何顺序匹配单词


Regex to match words in any order

我正在寻找一个正则表达式,可以按任何顺序匹配单词列表,除非遇到未列出的单词。代码将是有点

// match one two and three in any order
$pattern = '/^(?=.*'bone'b)(?=.*'btwo'b)(?=.*'bthree'b).+/';
$string = 'one three';
preg_match($pattern, $string, $matches);
print_r($matches); // should match array(0 => 'one', 1 => 'three')
// match one two and three in any order
$pattern = '/^(?=.*'bone'b)(?=.*'btwo'b)(?=.*'bthree'b).+/';
$string = 'one three five';
preg_match($pattern, $string, $matches);
print_r($matches); // should not match; array() 

也许你可以试试这个:

$pattern = '/'G's*'b(one|two|three)'b(?=(?:'s'b(?:one|two|three)'b)*$)/';
$string = 'one three two';
preg_match_all($pattern, $string, $matches);
print_r($matches[1]);

'G在每次匹配后重置匹配。

输出:

Array
(
    [0] => one
    [1] => three
    [2] => two
)

蝰蛇-7演示。

试试这个:

$pattern = '/^(?:'s*'b(?:one|two|three)'b)+$/';

您应该能够在不需要向前看的情况下做到这一点。

尝试类似

^(one|two|three|'s)+?$

以上将匹配onetwothree's空格字符。

如果需要全部包含"一、二、三"
而且没有不同的词,这行得通。

 # ^(?!.*'b[a-zA-Z]+'b(?<!'bone)(?<!'btwo)(?<!'bthree))(?=.*'bone'b)(?=.*'btwo'b)(?=.*'bthree'b)
 ^ 
 (?!
      .* 'b [a-zA-Z]+ 'b 
      (?<! 'b one )
      (?<! 'b two )
      (?<! 'b three )
 )
 (?= .* 'b one 'b )
 (?= .* 'b two 'b )
 (?= .* 'b three 'b )