python findall、finditer、fullmatch
1、findall
findall 是 re(正則表達式)模塊中的一個非常實用的函數。它用于在字符串中查找所有匹配給定正則表達式的子串。
findall工作流程

示例:
import re pattern = r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}' # 這是一個匹配電子郵件地址的正則表達式 text = "Please contact us at support@example.com or sales@example.org." # 這是我們將要搜索的目標字符串 matches = re.findall(pattern, text) for match in matches: print(match) # 遍歷所有匹配項,并打印出來
2、finditer
掃描整個字符串,返回所有與規則相匹配的子串組成的迭代器(每個元素是一個Match對象)。
返回值:迭代器(iterator),如果沒有匹配,返回空迭代器。
示例:
import re s = 'abc123abc456' result = re.finditer(r'\d+', s) for match in result: print(match.group()) # 輸出:123 456
返回值
123 456
3、fullmatch
-
作用:要求目標文本完全匹配規則,否則返回
None。 -
返回值:Match對象或
None。
import re s = '123abc' print(re.fullmatch(r'\d+', s)) # None,因為不是全數字 print(re.fullmatch(r'\d+abc', s)) # <re.Match object ...>
match和search(補充)
match:只在字符串開頭匹配,開頭不符合規則就返回None。search:在整個字符串查找,找到第一個符合規則的子串就返回Match對象。
import re str1 = 'http://www.baidu.com' finded = re.match('www', str1) print(finded)
解釋
re.match('www', str1) 規則:'www' 目標文本:'http://www.baidu.com' match方法只會在字符串開頭查找“www”。 但str1的開頭是'http://',不是'www',所以匹配失敗。 print(finded) 匹配失敗,finded為None,所以輸出:

浙公網安備 33010602011771號