how can I use regex to find a word containing the letter 'a' but it is not followed by the letter 'b'. python
The entire code is ad follows:-
import re
words = ["abcdef", "acdef", "cdeabc abcd cdeaf cdefa acdef acbfd"]
print(words)
for word in words:
print(word)
print("\t", re.findall(r"(\w*a(?!b)\w*)", word))
What we have used here is called negative lookahead. The (?!) sequence succeeds if it doesn't match the following character, but is not captured.
Explanation as per our problem's regular expression:
\w* is trying to match all the characters or digits before our negative lookahead.
a(?!b) will match all the words that contain the letter a not followed by b.
The following is the output of the above code snippet:
I hope this solved your query. If you have any doubt do let me know. Regards.
Get Answers For Free
Most questions answered within 1 hours.