1

我正在寻找一个正则表达式,它将以任何顺序匹配单词列表,除非遇到未列出的单词。该代码将类似于

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

4 回答 4

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 演示

于 2013-09-11T16:40:25.973 回答
2

试试这个:

$pattern = '/^(?:\s*\b(?:one|two|three)\b)+$/';
于 2013-09-11T16:32:48.137 回答
2

您应该能够做到这一点,而无需向前看。

尝试类似的模式

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

以上将匹配one, two, three, 或\s空白字符。

于 2013-09-11T16:20:18.880 回答
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 )
于 2013-09-11T18:11:51.010 回答