python-regexHow to regex match excluding a character in Python?
To regex match excluding a character in Python, you can use the re.search() function with the ^ and $ symbols. The ^ symbol indicates the start of the string, and the $ symbol indicates the end of the string. Any character that is not the character you want to exclude will be matched.
For example, to match a string that starts with Hello and ends with World but does not contain the letter a, you can use the following code:
import re
string = "Hello World"
if re.search("^Hello[^a]*World$", string):
print("Match found!")
Output example
Match found!
The code consists of the following parts:
import re: imports theremodule which contains there.search()function.string = "Hello World": assigns the string to be matched to thestringvariable.if re.search("^Hello[^a]*World$", string):: uses there.search()function to search for a match in thestringvariable. The regex pattern^Hello[^a]*World$matches any string that starts withHello, does not contain the lettera, and ends withWorld.print("Match found!"): prints the messageMatch found!if a match is found.
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...