Thanks to visit codestin.com
Credit goes to www.tutorialspoint.com

Python re.escape() method



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.

Syntax

Following 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 value

This method returns a string with all non-alphanumeric characters escaped

Example 1

Following 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\.htm

Example 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
Advertisements