Python – Regex Lookahead
Lookahead is used as an assertion in Python regular expressions to determine success or failure whether the pattern is ahead i.e to the right of the parser’s current position. They don’t match anything. Hence, they are called as zero-width assertions.
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course
# Positive lookahead (?=<lookahead_regex>)
Pattern: geeks Pattern found from index: 0 to 5
The lookahead assertion (?=[a-z]) specifies that what follows geeks must be a lowercase alphabetic character. In this case, it’s the character f, a match is found.
In the above example, the output is None because the next character after geeks is 1. It is not a lowercase alphabetic character.
Lookahead portion is not part of the search string. Hence, it is termed as zero width assertion. They are important when you don’t want the output to return lookahead portion present in search string but want to use it to match pattern which is followed by a particular section. Below example will make this clear.
Using lookahead: geeks Without using lookahead: geeksf
Using lookahead the output generated is ‘geeks’ whereas without using lookahead the output generated is geeksf. The f is consumed by regex and it becomes part of the search string.
Negative lookahead is opposite of lookahead. It is to assure that the search string is not followed by <lookahead_regex>.
# Negative Lookahead (?!<lookahead_regex>)
Positive Lookahead: geeks Negative Lookahead: geeks
In the above example, the output is geeks because search string geeks here is not followed by lowercase letters.