St3an
St3an

Reputation: 806

positive lookahead works whereas negative lookbehind doesn't

Let's assume I want to match a sentence like :

Home is now behind you, the world is ahead!

this way:

^.*(?<=(H|h)ome).*(w|W)orld.*(\.|!)$

This seems to work fine. (see on regex101)

Now let's assume I'd like to exclude sentences in which the words 'home' and 'world' come in the reverse order:

World is now behind you, the home is ahead!

I tried this (regex101):

^.*(?<!(w|W)orld).*(H|h)ome.*(\.|!)$

This one doesn't work... :-(

Could anyone please explain how to achieve it with negative lookbehinds or by another mean ?...

Upvotes: 0

Views: 495

Answers (2)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521103

I would phrase your requirement as:

^(?i)(?!.*\bworld\b.*\bhome\b).*\bhome\b.*\bworld\b.*$

Demo

The negative lookahead at the start of the pattern asserta that world is not followed by home in that order.

Upvotes: 1

boky
boky

Reputation: 835

Positive and negative lookahead/lookbehind depend on your regex processor. Not all processors support this feature.

If I remember correctly, negative lookbehind is seldom implemented.

I have tried your regex at https://regexr.com and it seems to work correctly.

Upvotes: 0

Related Questions