Python正则表达式二

1)re的matche方法和search方法

# 正则对象的match匹配(推荐使用)
# re.match 尝试从字符串的起始位置匹配一个模式,如果不是起始位置匹配成功的话,match()就返回none
# match(string[, pos[, endpos]])
# string:匹配使用的文本,
# pos: 文本中正则表达式开始搜索的索引。及开始搜索string的下标
# endpos: 文本中正则表达式结束搜索的索引。
# 如果不指定pos,默认是从开头开始匹配,如果匹配不到,直接返回None

import re
reg = re.compile(r'\w*((hello w.*)(hello f.*))')
# print(dir(reg))
a = 'hello world hello feng'
result = reg.match(a)
print(result.groups())  # 运行结果:('hello world hello feng', 'hello world ', 'hello feng')

b = 'aa' + a
result2 = reg.match(b)
print(result2.groups())  # 运行结果:('hello world hello feng', 'hello world ', 'hello feng')

# 正则对象的search方法
# search(string[, pos[, endpos]])
# 这个方法用于查找字符串中可以匹配成功的子串。从string的pos下标处起尝试匹配pattern,
# 若无法匹配,则将pos加1后重新尝试匹配;直到pos=endpos时仍无法匹配则返回None
result3 = reg.search(b)
print(result3.groups())  # 运行结果:('hello world hello feng', 'hello world ', 'hello feng')

# re.match只匹配字符串的开始,如果字符串开始不符合正则表达式,则匹配失败,函数返回None;
# 而re.search匹配整个字符串,直到找到一个匹配

2)re的split、findall、finditer方法

import re
p = re.compile(r'\d+')
a_str = 'one1two2three3four4'

# 正则对象的split方法
# split(string[, maxsplit])
# 按照能够匹配的子串以string分割后返回列表。maxsplit用于指定最大分割次数,不指定将全部分割
print(p.split(a_str))  # 运行结果:['one', 'two', 'three', 'four', ''],把p的正则当成是分隔符

# findall(string[, pos[, endpos]]) 
# 查找符合条件的string,以列表形式返回全部能匹配的字符串
print(p.findall(a_str))  # 运行结果:['1', '2', '3', '4']

# finditer(string[, pos[, endpos]])
# 搜索string,返回一个顺序访问每一个匹配结果(Match对象)的迭代器
for i in p.finditer(a_str):
    print(i.group())

3)re的matche对象

# re的match对象
import re
prog = re.compile(r'(?P<tagname>abc)(.*)(?P=tagname)')
result4 = prog.match('abclfjlad234sjldabc')
print(result4)  # <_sre.SRE_Match object at 0x00000000029FFE88>
print(result4.groups())  # ('abc', 'lfjlad234sjld')
print result4.group('tagname')  # abc
print(result4.group(2))  # lfjlad234sjld
print(result4.groupdict())  # {'tagname': 'abc'}
# 1、可以看到result1已经由字符串转换成了一个正则对象
# 2、resule.groups()可以查看出来所有匹配到的数据,每个()是一个元素,最终返回一个tuple
# 3、group()既可以通过下标(从1开始)的方式访问,也可以通过分组名进行访问。
# 4、groupdict只能显示有分组名的数据

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值