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 there
module which contains there.search()
function.string = "Hello World"
: assigns the string to be matched to thestring
variable.if re.search("^Hello[^a]*World$", string):
: uses there.search()
function to search for a match in thestring
variable. 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 perform a zero length match with Python Regex?
- How to get all matches from a regex in Python?
- How to match a YYYY-MM-DD date with Python Regex?
- How to use word boundaries in Python Regex?
- How to match a year with Python Regex?
- How to match whitespace in Python regex?
- How to validate an IP using Python regex?
- How to match a UUID using Python regex?
- How to match a URL path using Python regex?
- How to match a URL using Python regex?
See more codes...