The Python re.escape() method is used to escape all non-alphanumeric characters in a given pattern string. This is particularly useful when we need to match a string that contains special characters such as punctuation or regex operators, which would otherwise be interpreted as part of the regular expression syntax.
By escaping these characters the method re.escape() ensures that they are treated as literal characters in the pattern.
SyntaxFollowing is the syntax and parameters of Python re.escape() method −
re.subn(pattern, repl, string, count=0, flags=0)Parameter
The python re.escape() method accepts a single parameter, pattern which is a string to be escaped.
Return valueThis method returns a string with all non-alphanumeric characters escaped
Example 1Following is the basic example of re.escape() method in which the special characters '.' and '*' are escaped −
import re pattern = 'hello.*tutorialspoint.' escaped_pattern = re.escape(pattern) print(escaped_pattern)Output
hello\.\*tutorialspoint\.Example 2
In this example all special characters in the URL are escaped with the help of re.escape() method −
import re url = 'https://www.tutorialspoint.com/index.htm' escaped_url = re.escape(url) print(escaped_url)Output
https://www\.tutorialspoint\.com/index\.htmExample 3
Here in this example an escaped string is combined with other patterns to form a complex regular expression −
import re special_string = 'Hello$^Tutorialspoint' escaped_string = re.escape(special_string) combined_pattern = f"Prefix {escaped_string} Suffix" print(combined_pattern) string = 'This is Prefix Hello$^Tutorialspoint Suffix in the text.' match = re.search(combined_pattern, string) print(match.group())Output
Prefix Hello\$\^Tutorialspoint Suffix Prefix Hello$^Tutorialspoint Suffix
python_modules.htm
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4