python-regexHow to escape regex in Python?
To escape regex in Python, you can use the re.escape()
function. This function takes a string as an argument and returns a string with all non-alphanumeric characters escaped.
For example:
import re
string = 'This is a string with *special* characters'
escaped_string = re.escape(string)
print(escaped_string)
Output example
This\ is\ a\ string\ with\ \*special\*\ characters
The re.escape()
function:
- takes a string as an argument
- returns a string with all non-alphanumeric characters escaped
Helpful links
More of Python Regex
- How to validate an IP using Python regex?
- How to replace all using Python regex?
- How to match a YYYY-MM-DD date with Python Regex?
- How to match whitespace in Python regex?
- How to match a URL using Python regex?
- How to replace in a file using Python regex?
- How to replace using Python regex?
- How to match a plus sign in Python regex?
- How to match zero or one occurence in Python regex?
- How to ignore case in Python regex?
See more codes...