Skip to content
Advertisement

Python regex: Negative look-ahead with selection of different length strings

I’m searching for a Regex pattern in Python 3.8 that matches a sequence of strings if and only if it’s not followed by a selection of other strings. For example, I want to match the pattern “<fruit> and <fruit>” only if the second fruit isn’t followed by “ice” or “juice”:

JavaScript

However, this pattern has problems if the selection of strings in the negative look-ahead aren’t of the same length:

JavaScript

I ultimately want to use sub to replace the matched sequence only if it’s not followed by the selection of strings mentioned above. Is it possible to change the behavior of the negative look-ahead to match as much as possible?

Advertisement

Answer

You only need a “negative look-ahead assertion”.

JavaScript

The following pattern does the job you want.

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement