Python 中 re.match()、re.search() 和 re.findall() 方法有什麼區別?
re.match()、re.search() 和 re.findall() 是 Python 模組 re (Python 正則表示式) 的方法。
re.match() 方法
re.match() 方法 僅在字串開頭匹配。例如,在字串“TP Tutorials Point TP”上呼叫 match() 並查詢模式“TP”將匹配。
示例
import re result = re.match(r'TP', 'TP Tutorials Point TP') print result.group(0)
輸出
TP
re.search() 方法
re.search() 方法 與 re.match() 類似,但它不侷限於僅在字串開頭查詢匹配項。
示例
import re result = re.search(r'Tutorials', 'TP Tutorials Point TP') print result.group(0)
輸出
Tutorials
re.findall() 方法
re.findall() 用於獲取所有匹配模式的列表。它從給定字串的開頭或結尾搜尋。如果我們使用 findall 方法在一個給定字串中搜索一個模式,它將返回該模式的所有出現。在搜尋模式時,建議始終使用 re.findall(),它兼具 re.search() 和 re.match() 的功能。
示例
import re result = re.search(r'TP', 'TP Tutorials Point TP') print result.group()
輸出
TP
廣告