Skip to content
Advertisement

Extract all matches unless string contains

I am using the re package’s re.findall to extract terms from strings. How can I make a regex to say capture these matches unless you see this substring (in this case the substring "fake"). I attempted this via a anchored look-ahead solution.

Current Output:

JavaScript

Desired Output

JavaScript

I could accomplish this with an if/else but was wondering how to use a pure regex to solve this?

JavaScript

Advertisement

Answer

Since re does not support unknown length lookbehind patterns, the plain regex solution is not possible. However, the PyPi regex library supports such lookbehind patterns.

After installing PyPi regex, you can use

JavaScript

See the regex demo.

Details:

  • (?<!fake.*) – a negative lookbehind that fails the match if there is fake string followed with any zero or more chars other than line break chars as many as possible immediately to the left of the current location
  • (man[a-z]?b|dog)man + a lowercase ASCII letter followed with a word boundary or dog string
  • (?!.*fake) – a negative lookahead that fails the match if there are any zero or more chars other than line break chars as many as possible and then a fake string immediately to the left of the current location.

In Python:

JavaScript
Advertisement