0

仅当字符串milk之前没有任何或全部 4 个特定单词(为简单起见,将这些单词称为 AA、BB、CC、DD)时,我才想要匹配。

所以I went to the store and bought some milk会匹配,但以下不会:

AA went to the store and bought some milk或者BBCCDDmilk

换句话说,我如何得到相反的响应:/.*?(AA|BB|CC|DD).*?milk/

我想我应该在某个地方放一个插入符号,但一直无法弄清楚。谢谢你。

4

1 回答 1

1

Description

This regex will validate each line in the given text to ensure it doesn't have the string {aa, bb, cc, dd} preceding the string milk on any single line. Matching lines are then returned. Note: the examples in OP show that the matched "words" are simply strings, and white space and word boundaries do not matter.

^(?!.*?(?:AA|BB|CC|DD).*?milk).*

  • ^ anchor this match to the start to of the line
  • (?! start negative look ahead, if my contents match successfully then I'll fail
  • .*?(?:AA|BB|CC|DD).*?milk look for strings aa bb cc dd followed by string milk
  • ) end the lookahead
  • .* match the entire sentence

enter image description here

PHP Code Example:

Input Text

AA went to the store and bought some milk
BBCCDDmilk
I went to the store and bought some milk
Aardvarks like milk

Code

<?php
$sourcestring="your source string";
preg_match_all('/^(?!.*?(?:AA|BB|CC|DD).*?milk).*/im',$sourcestring,$matches);
echo "<pre>".print_r($matches,true);
?>

Matches

$matches Array:
(
    [0] => Array
        (
            [0] => I went to the store and bought some milk
        )

)
于 2013-06-21T13:31:07.800 回答