python findall、finditer、fullmatch

1、findall

 

findall 是 re(正则表达式)模块中的一个非常实用的函数。它用于在字符串中查找所有匹配给定正则表达式的子串。

 

findall工作流程

 

image

 示例:

 

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 ...>

matchsearch(补充)

  • 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,所以输出:

 

posted @ 2025-08-09 00:52  星火撩原  阅读(31)  评论(0)    收藏  举报