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 match a YYYY-MM-DD date with Python Regex?
- How to match a UUID using Python regex?
- How to match a year with Python Regex?
- How to replace all using Python regex?
- How to use word boundaries in Python Regex?
- How to remove numbers from a string using Python regex?
- How to get a group from a regex in Python?
- How to match a URL path using Python regex?
- How to use quantifiers in Python regex?
- How to quote in Python regex?
See more codes...