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:
import re
for x in ['a man dogs', "fake: too many dogs", 'hi']:
print(re.findall(r"(man[a-z]?b|dog)(?!^.*fake)", x, flags=re.IGNORECASE))
## ['man', 'dog']
## ['many', 'dog']
## []
Desired Output
## ['man', 'dog'] ## [] ## []
I could accomplish this with an if/else but was wondering how to use a pure regex to solve this?
for x in ['a man dogs', "fake: too many dogs", 'hi']:
if re.search('fake', x, flags=re.IGNORECASE):
print([])
else:
print(re.findall(r"(man[a-z]?b|dog)", x, flags=re.IGNORECASE))
## ['man', 'dog']
## []
## []
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
(?<!fake.*)(man[a-z]?b|dog)(?!.*fake)
See the regex demo.
Details:
(?<!fake.*)– a negative lookbehind that fails the match if there isfakestring 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 ordogstring(?!.*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 afakestring immediately to the left of the current location.
In Python:
import regex
for x in ['a man dogs', "fake: too many dogs", 'hi']:
print(regex.findall(r"(?<!fake.*)(man[a-z]?b|dog)(?!.*fake)", x, flags=re.IGNORECASE))