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 use word boundaries in Python Regex?
- How to match HTML tags with regex in Python?
- How to match the end of a line with regex in Python?
- How to match a YYYY-MM-DD date with Python Regex?
- How to match a URL path using Python regex?
- How to remove numbers from a string using Python regex?
- How to match a question mark in Python regex?
- How to replace in a file using Python regex?
- How to replace all using Python regex?
- How to match a hex color with regex in Python?
See more codes...