Python re.escape() Method
re.escape()is Pythonremodule used forescaping regular expression special charactersfunction.
It will take all regular expression special characters in the string (such as.、*、?etc.) and escape them, making them be treated as ordinary characters.
Word Definitions: escapemeans "escape" and "flee".
Basic Syntax and Parameters
Syntax Format
re.escape(string)
Parameter Description
- string: The string to be escaped
Function Description
- Return Value: Returns the escaped string.
Examples
Example 1: Basic Usage
Example
import re
# Escape a string containing special characters
text = "example.com?foo=1"
result = re.escape(text)
print("Original:", text)
print("Escaped:", result)
# Escape a string containing special characters
text = "example.com?foo=1"
result = re.escape(text)
print("Original:", text)
print("Escaped:", result)
Expected output:
原始: example.com?foo=1 转义后: example\.com\?foo\=1
Example 2: Use in Search
Example
import re
# Search for a string containing a dot (literal search, not regex)
text = "File path: C:\\Users\\test.txt"
# Escape backslash and dot
pattern = re.escape("C:\\Users\\test.txt")
result = re.search(pattern, text)
if result:
print("Found:", result.group())
# Search for a string containing a dot (literal search, not regex)
text = "File path: C:\\Users\\test.txt"
# Escape backslash and dot
pattern = re.escape("C:\\Users\\test.txt")
result = re.search(pattern, text)
if result:
print("Found:", result.group())
Expected output:
找到: C:\Users\test.txt
Example 3: Compare Escaping and Non-escaping
Example
import re
text = "price: $100"
# Without escaping - $ is a special character in regex (end of line)
result1 = re.findall(r'$100', text)
# After escaping - $ is treated as an ordinary character
result2 = re.findall(re.escape('$100'), text)
print("Without escaping:", result1)
print("Escaped:", result2)
text = "price: $100"
# Without escaping - $ is a special character in regex (end of line)
result1 = re.findall(r'$100', text)
# After escaping - $ is treated as an ordinary character
result2 = re.findall(re.escape('$100'), text)
print("Without escaping:", result1)
print("Escaped:", result2)
Expected output:
不转义: [] 转义后: ['$100']
Example 4: Handling User Input
Example
import re
# Special characters that the user may input
user_input = "python*"
text = "python* is great"
# Escape the user input before searching
pattern = re.escape(user_input)
result = re.search(pattern, text)
print("Search result:", result.group() if result else "Not found")
# Special characters that the user may input
user_input = "python*"
text = "python* is great"
# Escape the user input before searching
pattern = re.escape(user_input)
result = re.search(pattern, text)
print("Search result:", result.group() if result else "Not found")
Expected output:
查找结果: python*
Other Extensions
Python re Module