pythonre教程_Python之re操作实例教程

1.re.search():search返回的是查找结果的对象(按顺序找到第一个成功匹配的结果后就不往后查找了,没有查找到返回None),可以使用group()或groups()方法得到匹配成功的字符串。

①group()默认返回匹配成功的整个字符串(忽略pattern中的括号),也可以指定返回匹配成功的括号中第几个字符串(从1开始计数);

②groups()以元组的形式返回匹配成功的pattern中括号中的内容,若pattern中没有括号,则返回成功匹配的字符串对应的空元组。

1 >>> string = 'python' 2 >>> import re 3 >>> result = re.search(r'(yt)h(o)', string) 4 >>> result 5 <_sre.sre_match object at> 6 >>> result.group() 7 'ytho' 8 >>> result.group(0) # 参数0无效 9 'ytho'10 >>> result.group(1) # 从1开始计数11 'yt'12 >>> result.group(2)13 'o'14 >>> result.groups()15 ('yt', 'o')16 >>> result.groups(0) # 传入参数无效17 ('yt', 'o')18 >>> result.groups(1)19 ('yt', 'o')20 >>>

2. re.finditer():返回全部查找结果的迭代器(若没有匹配成功的字符串,则返回一个空的迭代器),每个迭代对象同样可以使用group()和groups()获取成功匹配的结果。

1 >>> string = 'one11python, two22, three33python ' 2 >>> result = re.finditer(r'(\d+)(python)', string) 3 >>> for p in result: 4 print(p.group()) 5 6 7 11python 8 33python 9 >>> for p in result:10 print(p.group(2))11 12 13 python14 python15 >>> for p in result:16 print(p.groups()) # 若是pattern中没有括号,则返回的是每个迭代器对应的空元组。17 18 19 ('11', 'python')20 ('33', 'python')

3. re.findall():以列表的形式返回查找到的全部字符串(若没有查找到能成功匹配的字符串,则返回空的列表)。

1 >>> string = 'one11python, two22, three33python '2 >>> result = re.findall(r'\d+python', string)3 >>> result4 ['11python', '33python']5 >>> result = re.findall(r'(\d+)(python)', string)6 >>> result7 [('11', 'python'), ('33', 'python')]

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值