0

I want a match only if the string milk is not preceded at any time by any or all of 4 specific words (for simplicity call these words AA, BB, CC, DD).

So I went to the store and bought some milk would match but the following wouldn't:

AA went to the store and bought some milk or BBCCDDmilk

Put another way, how do I get the opposite response of: /.*?(AA|BB|CC|DD).*?milk/

I think I'm supposed to put a caret somewhere but haven't been able to figure it out. Thank you.

Alan Moore
  • 73,866
  • 12
  • 100
  • 156

1 Answers1

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
        )

)
Ro Yo Mi
  • 14,790
  • 5
  • 35
  • 43
  • The original question said "So I went to the store and bought some milk would match", but the regex above would not match that, at least in my use of it. Surely the negative match needs to be closed before ".>?milk", in order to allow for finding strings that include milk. So for me what worked was "^(?!.*?(?:AA|BB|CC|DD)).*?milk.* – Beel Oct 20 '13 at 10:26
  • 1
    Having said that, this was a fabulous post, it showed me how to solve my problem, and much better than the other post referenced as a duplicate. Thumbs up! – Beel Oct 20 '13 at 10:35
  • Fail. It matches lines that DON'T contain milk! – CommaToast Nov 12 '14 at 05:01