python-regexHow to regex match excluding a word in Python?
To regex match excluding a word in Python, you can use the re.search() function with a negative lookahead assertion. The negative lookahead assertion is a special syntax that allows you to specify a pattern that should not be matched.
For example, the following code will match any string that contains the word cat but not the word dog:
import re
string = 'The cat is sleeping'
match = re.search(r'cat(?!.*dog)', string)
if match:
print('Match found:', match.group())
Output example
Match found: cat
The code consists of the following parts:
import re: imports theremodule, which provides functions for working with regular expressions.string = 'The cat is sleeping': defines a string to search.match = re.search(r'cat(?!.*dog)', string): uses there.search()function to search for the patterncat(?!.*dog)in the string. The(?!.*dog)part is a negative lookahead assertion, which means that the pattern should not be followed by the worddog.if match:: checks if a match was found.print('Match found:', match.group()): prints the matched string.
Helpful links
More of Python Regex
- How to match a plus sign in Python regex?
- How to get a group from a regex in Python?
- How to replace all using Python regex?
- How to match a float with regex in Python?
- How to match whitespace in Python regex?
- How to match digits with Python regex?
- How to match a YYYY-MM-DD date with Python Regex?
- How to use word boundaries in Python Regex?
- How to replace in a file using Python regex?
- How to match a question mark in Python regex?
See more codes...