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 the- remodule which contains the- re.search()function.
- string = "Hello World": assigns the string to be matched to the- stringvariable.
- if re.search("^Hello[^a]*World$", string):: uses the- re.search()function to search for a match in the- stringvariable. The regex pattern- ^Hello[^a]*World$matches any string that starts with- Hello, does not contain the letter- a, and ends with- World.
- print("Match found!"): prints the message- Match found!if a match is found.
Helpful links
More of Python Regex
- How to replace in a file using Python regex?
- How to match a question mark in Python regex?
- How to match a YYYY-MM-DD date with Python Regex?
- How to get a group from a regex in Python?
- How to match whitespace in Python regex?
- How to ignore case in Python regex?
- How to get the href attribute value from a regex in Python?
- How to use word boundaries in Python Regex?
- How to remove numbers from a string using Python regex?
- How to match a plus sign in Python regex?
See more codes...