先写例子,再总结
(1)re.search()方法
import re
string = "John Doe: 25 years, Jane Smith: 30 years"
pattern = r"(\w+)\s(\w+):\s(\d+)\syears"
match = re.search(pattern, string)
if match:
print(match.group(0)) # 整个匹配项 "John Doe: 25 years"
print(match.group(1)) # 第一个分组的内容 "John"
print(match.group(2)) # 第二个分组的内容 "Doe"
print(match.group(3)) # 第三个分组的内容 "25"
(2)re.findall()方法
import re
string = "John Doe: 25 years, Jane Smith: 30 years"
pattern = r"(\w+)\s(\w+):\s(\d+)\syears"
matches = re.findall(pattern, string)
for match in matches:
print(match) # ('John', 'Doe', '25'), ('Jane', 'Smith', '30')
浅浅总结一下:
re.search()
(1)用于在给定的字符串中查找第一个匹配项
(2)如果正则表达式中有多个分组,它只返回第一个匹配项的信息。
(3)如果匹配成功,search函数
返回一个 Match
对象,可使用group()
方法来匹配分组中的内容
(4)如果没找到匹配项,则返回 None
。
re.findall()
(1)findall
函数用于在给定字符串中查找所有匹配项,并返回一个包含所有匹配项的列表。
(2)如果正则表达式中有多个分组,则返回每个匹配项的所有分组内容。
(3) 如果列表中每一个元素表示一个匹配项,元素顺序与字符串中出现顺序相对应。
(4) 分组内容以元组形式返回,其中每个元组表示一个匹配项的分组内容。
(5) 如果没有匹配项,返回一个空列表。