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 use word boundaries in Python Regex?
- How to perform a zero length match with Python Regex?
- How to match whitespace in Python regex?
- How to ignore case in Python regex?
- How to get all matches from a regex in Python?
- How to make a case insensitive match with Python regex?
- How to match a URL path using Python regex?
- How to get a group from a regex in Python?
- How to match a plus sign in Python regex?
See more codes...