Python - AI 助手

Python re.escape() 方法



Python re.escape() 方法用於轉義給定模式字串中的所有非字母數字字元。當我們需要匹配包含特殊字元(例如標點符號或正則表示式運算子)的字串時,這特別有用,否則這些特殊字元會被解釋為正則表示式語法的一部分。

透過轉義這些字元,re.escape() 方法確保它們在模式中被視為字面字元。

語法

以下是 Python re.escape() 方法的語法和引數:

re.subn(pattern, repl, string, count=0, flags=0)

引數

Python re.escape() 方法接受單個引數 pattern,它是要轉義的字串。

返回值

此方法返回一個所有非字母數字字元都被轉義的字串。

示例 1

以下是 re.escape() 方法的基本示例,其中特殊字元“.”和“*”被轉義:

import re

pattern = 'hello.*tutorialspoint.'
escaped_pattern = re.escape(pattern)
print(escaped_pattern)     

輸出

hello\.\*tutorialspoint\.

示例 2

在這個示例中,URL 中的所有特殊字元都藉助 re.escape() 方法進行了轉義:

import re

url = 'https://tutorialspoint.tw/index.htm'
escaped_url = re.escape(url)
print(escaped_url)

輸出

https://www\.tutorialspoint\.com/index\.htm

示例 3

在此示例中,轉義的字串與其他模式組合以形成複雜的正則表示式:

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()) 

輸出

Prefix Hello\$\^Tutorialspoint Suffix
Prefix Hello$^Tutorialspoint Suffix
python_modules.htm
廣告