18 Python Lookbehind
18 Python Lookbehind
• Positive Lookbehind
• Example
• Neagative Lookbehind
• Example
Positive Lookbehind #
(?<=regex) Matches at a position if the pattern inside the lookbehind can be
matched ending at that position.
Example #
Consider the following string:
begin:learner1:scientific:learner2:scientific:learner3:end
import re
string = "begin:learner1:scientific:learner2:scientific:learner3:end"
print re.findall(r"(?<=learner\d:)(\b\w*\b)", string)
Neagative Lookbehind #
Similar to positive lookbehind, (?<!regex) matches at a position if the pattern
inside the lookbehind cannot be matched ending at that position.
Example #
Let’s now proceed to an example, where we find the word ( begin ), not
preceded by the words learner{1-3} .
import re
string = "begin:learner1:scientific:learner2:scientific:learner3:end"
print re.findall(r"^(?<!learner\d:)(\b\w*\b)", string)