Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Negative lookahead - fail if both of two words are found in the input

Tags:

regex

I need a negative lookahead expression, but I can't make it work :( I hope someone can help me. I need an expression which is true until the sample does not contain 2 words anywhere in the sample. For example the 2 words pie donuts:

i sure like eating pie, but i love donuts very much
---> false
i sure like eating but i love donuts very much
---> true
i sure like eating pie, but i love hamburger very much
---> true
i sure like eating donuts, but i love pie very much
---> false
i sure like eating piedonuts very much
---> false

I have tried it in many forms, but it does not work.

like image 794
user1892024 Avatar asked Dec 03 '25 17:12

user1892024


2 Answers

You could do this with two positive lookaheads that are nested inside a negative one (all starting from the beginning of your string):

^(?!(?=.*pie)(?=.*donuts))

So the inner lookaheads require to match both words. If they do the contents of the negative lookahead will match, so the lookahead itself will cause the pattern to fail.

If you can have line breaks in your input, make sure to use the s or dotall option (otherwise, . does not match line breaks).

like image 140
Martin Ender Avatar answered Dec 06 '25 08:12

Martin Ender


Much simpler than using negative lookahead is simply having two regexes and checking that they don't match.

You didn't specify the language, but here is a simple example in Perl:

use warnings;
use strict;

while (<DATA>)
{
    my $match = (/pie/ and /donuts/) ? 'false' : 'true';
    print $_;
    print "--> $match\n";
}

__DATA__
i sure like eating pie, but i love donuts very much
i sure like eating but i love donuts very much
i sure like eating pie, but i love hamburger very much
i sure like eating donuts, but i love pie very much
i sure like eating piedonuts very much
like image 40
dan1111 Avatar answered Dec 06 '25 08:12

dan1111



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!