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