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

时间:2013-09-11 16:14:46

标签: php regex preg-match

我正在寻找一个与任何顺序的单词列表匹配的正则表达式, 除非遇到未列出的单词。代码将是一些东西

// 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() 

4 个答案:

答案 0 :(得分:4)

也许你可以试试这个:

$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
)

viper-7 demo

答案 1 :(得分:2)

你应该能够在不需要展望的情况下做到这一点。

尝试类似

的模式
^(one|two|three|\s)+?$

上述内容将与onetwothree\s空格字符匹配。

答案 2 :(得分:2)

试试这个:

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

答案 3 :(得分:0)

如果需要全部“一,二,三” 并且没有一个不同的词有效。

 # ^(?!.*\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 )