Negative lookahead and negative lookbehind and multiple characters in PCRE

pcre, php, regex

Solution

(*SKIP)(*F) Magic (No Lookaheads Needed)

Use this:

(\baa\b).*?\1(*SKIP)(*F)|\bbb\w+\b

See the match in the demo.

This problem is a classic case of the technique explained in this question to "regex-match a pattern, excluding..."

The left side of the alternation `|` matches complete `aa ... aa` strings then deliberately fails, after which the engine skips to the next position in the string. The right side matches the `bb...` words you want, and we know they are the right ones because they were not matched by the expression on the left.

Reference

- How to match (or replace) a pattern except in situations s1, s2, s3...

- Article about matching a pattern unless...

Problem

I have the following text: ``` aabbaa aa bbc aa bbg aa bbd aa ``` I would like to find words that `starts with bb` that are `not between aa and aa` regardless of whitespaces preceding or following matching word using PCRE . In the above example only `bbg` should be matched. I have created the following pattern: ``` (?<!aa)bb(\w)*(?!aa) ``` However only aabbaa is not matched and other do. I don't know how can I use `\s*` inside negative look ahead/behind to get desired result. It seems it cannot be simple done using: ``` (?<!aa\s*)bb(\w)*(?!\s*aa) ``` How can it be done?

Original source

Related problems