Python re.escape() Method
re.escape() is a function in the Python re module used toEscape regular expression special characters.
It escapes all regular expression special characters in a string (such as .、*、? , etc.) so that they are treated as ordinary characters.
Word meaning: escape means "to escape".
Basic syntax and parameters
Syntax format
re.escape(string)
Parameter Description
- string: The string to escape
Function description
- Return Value: Returns the escaped string.
Example
Example 1: basic usage
Example
import
re
Escape a string containing special characters
text
=
"example.com?foo=1"
result
=
re
.
escape
(
text
)
(
"Original:"
,
text
)
(
"Escaped:"
,
result
)
Expected output:
原始: example.com?foo=1
转义后: example\.com\?foo\=1
Example 2: use in a search
Example
import
re
Search for a string containing a dot (a literal search, not a regular expression)
text
=
"File path: C:\\Users\\test.txt"
Escape backslashes and dots
pattern
=
re
.
escape
(
"C:\Users\test.txt"
)
result
=
re
.
search
(
pattern
,
text
)
if
result:
(
"Found:"
,
result.
group
(
)
)
Expected output:
找到: C:\Users\test.txt
Example 3: comparison between escaping and not escaping
Example
import
re
text
=
"price: $100"
Without escaping - $ is a special character in regular expressions (end of line)
result1
=
re
.
findall
(
r
'$100'
,
text
)
After escaping - $ is treated as an ordinary character
result2
=
re
.
findall
(
re
.
escape
(
'$100'
)
,
text
)
(
"Without escaping:"
,
result1
)
(
"Escaped:"
,
result2
)
Expected output:
不转义: []
转义后: ['$100']
Example 4: handling user input
Example
import
re
Special characters the user may enter
user_input
=
"python*"
text
=
"python* is great"
Escape the user input before searching
pattern
=
re
.
escape
(
user_input
)
result
=
re
.
search
(
pattern
,
text
)
(
"Search result:"
,
result.
group
(
)
if
result
else
"Not found"
)
Expected output:
查找结果: python*
Python re Module