python-regexHow to use negative lookbehind in Python regex?
Negative lookbehind is a feature of regular expressions that allows you to match a pattern only if it is not preceded by another pattern. It is supported in Python through the re module.
Example
import re
# Match any word that is not preceded by "not"
pattern = r"(?<!not)\b\w+\b"
string = "This is not a test"
match = re.search(pattern, string)
if match:
print(match.group())
Output example
This
Code explanation
(?<!not)- Negative lookbehind assertion that matches only if the pattern is not preceded by "not"\b\w+\b- Matches any wordre.search(pattern, string)- Searches for the pattern in the stringmatch.group()- Returns the matched pattern
Helpful links
More of Python Regex
- How to replace a certain group using Python regex?
- How to get a group from a regex in Python?
- How to replace all using Python regex?
- How to match a question mark in Python regex?
- How to match a year with Python Regex?
- How to match a plus sign in Python regex?
- How to match whitespace in Python regex?
- How to replace in a file using Python regex?
- How to match a YYYY-MM-DD date with Python Regex?
- How to match a hex number with regex in Python?
See more codes...