Python – Regex Lookbehind
Regex Lookbehind is used as an assertion in Python regular expressions(re) to determine success or failure whether the pattern is behind i.e to the right of the parser’s current position. They don’t match anything. Hence, Regex Lookbehind and lookahead are termed as a zero-width assertion.
# Positive lookbehind (?<=<lookbehind_regex>) # Positive lookahead (?=<lookahead_regex>)
In this post we will talk about regex lookbehind.
f Pattern found from index 5 6
The regex lookbehind assertion (?<=geeks) specifies that what precedes before any word character(‘\w’) must be ‘geeks’ string. In this case, it’s the character ‘f’ before which ‘geeks’ string occurs.
In the above example, the output is None because there is no decimal digit preceded by ‘geeks’ string.
Lookbehind portion is not part of the search string. They are important when you don’t want the output to return lookbehind portion present in search string but want to use it to match pattern which is preceded by a particular section. Below example will make this clear:
Using lookbehind the output generated is ‘1’ whereas without using lookbehind the output generated is ‘s1’. Any word character (\w) which precedes any decimal digit is consumed by regex so it doesn’t become part of the search string.
Negative Lookbehind is the opposite of lookbehind. It is to assure that the search string is not preceded by <lookbehind_regex>.
(?<!<lookbehind_regex>) Negative Lookbehind
Please Login to comment...