python-regexHow to match any symbol except a given one with Python regex?
To match any symbol except a given one with Python regex, you can use the [^symbol] syntax. This syntax will match any character except the one specified. For example, to match any character except a, you can use the following code:
import re
string = "Hello World!"
match = re.search(r"[^a]", string)
print(match.group())
Output example
H
The code above uses the following parts:
import re: imports theremodule which provides regular expression matching operations.string = "Hello World!": creates a string variable to use for the example.match = re.search(r"[^a]", string): uses there.search()function to search for any character exceptain thestringvariable.print(match.group()): prints the first match found.
Helpful links
More of Python Regex
- How to match a question mark in Python regex?
- How to match whitespace in Python regex?
- How to replace in a file using Python regex?
- How to match a YYYY-MM-DD date with Python Regex?
- How to replace all using Python regex?
- How to get the href attribute value from a regex in Python?
- How to use word boundaries in Python Regex?
- How to get a group from a regex in Python?
- How to get all matches from a regex in Python?
See more codes...