正則表達(dá)式中,search() 和 findall() 函數(shù)是兩個(gè)常用的檢索函數(shù),它們的區(qū)別在于返回的結(jié)果不同。
search() 函數(shù)在文本中查找匹配項(xiàng),并返回第一個(gè)匹配項(xiàng)的位置和信息(即一個(gè) Match 對(duì)象),如果沒有找到,則返回 None。
例如,使用以下 Python 代碼在字符串 "The quick brown fox jumps over the lazy dog" 中查找第一個(gè)匹配 "fox" 的位置和信息:
import re
text = "The quick brown fox jumps over the lazy dog"
match = re.search(r'fox', text)
if match:
print("Match found at:", match.start())
else:
print("Match not found")
輸出結(jié)果為:Match found at: 16。即在字符串中從第 16 個(gè)位置開始匹配 "fox" 子字符串。
findall() 函數(shù)在文本中查找所有匹配項(xiàng),并以匹配結(jié)果組成的列表形式返回,如果沒有找到匹配項(xiàng),則返回空列表[]。
例如,使用以下 Python 代碼在字符串 "The quick brown fox jumps over the lazy dog" 中查找所有三個(gè)連續(xù)字母的單詞:
import re
text = "The quick brown fox jumps over the lazy dog"
matches = re.findall(r'\b\w{3}\b', text)
if matches:
print("Matches found:", matches)
else:
print("Matches not found")
輸出結(jié)果為:Matches found: ['The', 'fox', 'the', 'dog']。即找到了所有由三個(gè)字母構(gòu)成的單詞。
總之,如果只需要找到第一個(gè)匹配項(xiàng),使用 search();如果需要找到所有匹配項(xiàng),使用 findall()。