Skip to content

Latest commit

 

History

History
56 lines (51 loc) · 1.08 KB

Regex lookarounds (lookbehind lookahead).md

File metadata and controls

56 lines (51 loc) · 1.08 KB
created modified tags type status
2024-10-27T15:09
2025-02-19 09:01
regex
text
lookaround
lookahead
lookbehind
text-parsing
parsing
document
nlp
note
completed

Positive Lookahead

x(?=y) matches with x only if it is followed by y

import re 
re.findall(r"\b[a-z]+(?=\d+\b)", "abc69 def ghi4 jk20l xyz")
# ['abc', 'ghi']

Negative Lookahead

x(?!y) matches with x only if it is NOT followed by y

import re 
re.findall(r"\b[a-z]+(?!\d+\b)", "abc69 def ghi4 jk20l xyz")
# ['ab', 'def', 'gh', 'jk', 'xyz']

Positive Lookbehind

(?<=x)y matches with y only if it preceded by x

import re 
re.findall(r"(?<=[ck])\d+", "abc69 def ghi4 jk20l xyz")
# ['69', '20']

Negative Lookbehind

(?<!x)y matches with y only if it is NOT preceded by x

import re 
re.findall(r"(?<![a-z]{3})\d+", "abc69 def ghi4 jk20l xyz")
# ['9', '20']

References

Related

  • Links to other notes which are directly related go here