正则的match、searth、finditer和findall方法介绍
# 1.用来处理字符串,对字符串进行检索和替换
import re # 正则表达式模块
# match和searth方法,执行结果是一个match类型的对象
x = 'hello\\nworld'
print(x) # hello\nworld
y =re.search('\\\\',x)
print(y) # <re.Match object; span=(5, 6), match='\\'>
# 2.查找相关的方法
# 1.match:查找字符串,返回的结果是一个re.mattch对象
m1 = re.match(r'hello','hello world good morining')
print(m1) # <re.Match object; span=(0, 5), match='hello'>
m2 = re.match(r'good','hello world good morining')
print(m2) # None
# 2.search:查找字符串,返回的结果是一个re.mattch对象
m3 = re.search(r'hello','hello world good morining')
print(m3) # <re.Match object; span=(0, 5), match='hello'>
m4 = re.search(r'good','hello world good morining')
print(m3) # <re.Match object; span=(12, 16), match='good'>
# match和search共同点:
# 1).只对字符串查询一次
# 2).返回值类型都是re.match类型的对象
# 不同点:match是从头开始匹配,一旦匹配失败,就返回None;search是在整个字符串里搜索
# 3.finditer:在字符串中查找一个指定字符所有的匹配对象返回的结果是一个可迭代对象
甲 = re.finditer('x','klxdasxadfxidfasxdfidzxds')
for 乙 in 甲:
print(乙)
# <re.Match object; span=(2, 3), match='x'>
# <re.Match object; span=(6, 7), match='x'>
# <re.Match object; span=(10, 11), match='x'>
# <re.Match object; span=(16, 17), match='x'>
# <re.Match object; span=(22, 23), match='x'>
from collections.abc import Iterable
print(isinstance(甲, Iterable)) # True 判断是否是个一个可迭代对象
# 4.findall:把查找到的所有字符串结果放到列表中
丙 = 'klx45dasx78adfxidfasxdfidzxds'
print(re.findall(r'x\d+', 丙)) # ['x45', 'x78'] \d+表示数字 +表示一次或多次 *表示零次或多次
# 5.fullmatch # 完整匹配,字符串需要完全符合正则规则才会有结果,否则就是None
丁 = re.fullmatch(r'hello world','hello world')
print(丁) # <re.Match object; span=(0, 11), match='hello world'>
戊 = re.fullmatch(r'h.*d','hdasfafaddsfasdd')
print(戊) # <re.Match object; span=(0, 16), match='hdasfafaddsfasdd'>
match类的使用
# 调用 re.match re.search获取对re.finditer结果进行遍历,拿到的内容都是re.match类型对象
import re
m = re.search(r'm.*a', 'o3rjomiadas') # . 表示任意字符 * 出现任意次数
print(m) # <re.Match object; span=(5, 6), match='m'>
print(m.span()) # (5, 6) # 匹配到的结果字符串的开始和结束下标
print(m.group()) # miada #先匹配到结果再用group显示结果的内容
# 上面为什么不是匹配成mia而是miada呢? * 会尽可能多的匹配
# group方法表示正则表达式的分组
# 1.在正则表达式里使用()表示一个分组
# 2.如果没有分组,默认只有一组
# 3.分组的下标从0开始
print(m.group(0)) # miada 可以传参,表示第几个分组
m1 = re.search(r'(9.*)(0.*)(5.*7)','sf9dgs0fgsdfg5sdhft7gxjhdghs')
# 有4个分组
print(m1.group(0)) # 9dgs0fgsdfg5sdhft7 默认就是第0组,省略参数0
print(m1.group(1)) # 9dgs
print(m1.group(2)) # 0fgsdfg
print(m1.group(3)) # 5sdhft7
print(m1.groups()) # ('9dgs', '0fgsdfg', '5sdhft7') 把多组结果作为元组返回
# (?P<name>表达式) 可以给分组起一个名字
m2 = re.search(r'(9.*)(?P<姓名>0.*)(5.*7)', 'saf9asd0frgs5dgfe7sarfgwe')
print(m2.groupdict()) # {'姓名': '0frgs'} 作用是获取到分组组成的字典,如果没有起名字就是空字典
print(m2.group('姓名')) # 0frgs 可以使用group加字典的key获取到value
print(m2.span(2)) # (7, 12) 获取到指定分组的下标