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 match whitespace in Python regex?
- How to match a question mark in Python regex?
- How to match a year with Python Regex?
- How to match HTML tags with regex in Python?
- How to replace in a file using Python regex?
- How to match a hex number with regex in Python?
- How to use word boundaries in Python Regex?
- How to validate an IP using Python regex?
- How to match a UUID using Python regex?
- How to remove numbers from a string using Python regex?
See more codes...