侯体宗的博客
  • 首页
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

Python3正则匹配re.split,re.finditer及re.findall函数用法详解

Python  /  管理员 发布于 7年前   378

本文实例讲述了Python3正则匹配re.split,re.finditer及re.findall函数用法。分享给大家供大家参考,具体如下:

re.split re.finditer re.findall

@(python3)

官方 re 模块说明文档

re.compile() 函数

编译正则表达式模式,返回一个对象。可以把常用的正则表达式编译成正则表达式对象,方便后续调用及提高效率。

re 模块最离不开的就是 re.compile 函数。其他函数都依赖于 compile 创建的 正则表达式对象

re.compile(pattern, flags=0)

  • pattern 指定编译时的表达式字符串
  • flags 编译标志位,用来修改正则表达式的匹配方式。支持 re.L|re.M 同时匹配

flags 标志位参数

re.I(re.IGNORECASE)
使匹配对大小写不敏感

re.L(re.LOCAL)
做本地化识别(locale-aware)匹配

re.M(re.MULTILINE)
多行匹配,影响 ^ 和 $

re.S(re.DOTALL)
使 . 匹配包括换行在内的所有字符

re.U(re.UNICODE)
根据Unicode字符集解析字符。这个标志影响 \w, \W, \b, \B.

re.X(re.VERBOSE)
该标志通过给予你更灵活的格式以便你将正则表达式写得更易于理解。

示例:

import recontent = 'Citizen wang , always fall in love with neighbour,WANG'rr = re.compile(r'wan\w', re.I) # 不区分大小写print(type(rr))a = rr.findall(content)print(type(a))print(a)

findall 返回的是一个 list 对象

<class '_sre.SRE_Pattern'>
<class 'list'>
['wang', 'WANG']

re.split 函数

按照指定的 pattern 格式,分割 string 字符串,返回一个分割后的列表。

re.split(pattern, string, maxsplit=0, flags=0)

  • pattern compile 生成的正则表达式对象,或者自定义也可
  • string 要匹配的字符串
  • maxsplit 指定最大分割次数,不指定将全部分割
import restr = 'say hello world! hello python'str_nm = 'one1two2three3four4'pattern = re.compile(r'(?P<space>\s)') # 创建一个匹配空格的正则表达式对象pattern_nm = re.compile(r'(?P<space>\d+)') # 创建一个匹配空格的正则表达式对象match = re.split(pattern, str)match_nm = re.split(pattern_nm, str_nm, maxsplit=1)print(match)print(match_nm)

结果:

['say', ' ', 'hello', ' ', 'world!', ' ', 'hello', ' ', 'python']
['one', '1', 'two2three3four4']

re.findall() 方法

返回一个包含所有匹配到的字符串的列表。

  • pattern 匹配模式,由 re.compile 获得
  • string 需要匹配的字符串
import restr = 'say hello world! hello python'pattern = re.compile(r'(?P<first>h\w)(?P<symbol>l+)(?P<last>o\s)') # 分组,0 组是整个 world!, 1组 or,2组 ld!match = re.findall(pattern, str)print(match)

结果

[('he', 'll', 'o '), ('he', 'll', 'o ')]

re.finditer 、re.findall

re.finditer(pattern, string[, flags=0])
re.findall(pattern, string[, flags=0])

  • pattern compile 生成的正则表达式对象,或者自定义也可
  • string 要匹配的字符串

findall 返回一个包含所有匹配到的字符的列表,列表类以元组的形式存在。

finditer 返回一个可迭代对象。

示例一:

pattern = re.compile(r'\d+@\w+.com') #通过 re.compile 获得一个正则表达式对象result_finditer = re.finditer(pattern, content)print(type(result_finditer))print(result_finditer) # finditer 得到的结果是个可迭代对象for i in result_finditer: # i 本身也是可迭代对象,所以下面要使用 i.group() print(i.group())result_findall = re.findall(pattern, content)print(type(result_findall)) # findall 得到的是一个列表print(result_findall)for p in result_finditer: print(p)

输出结果:

<class 'callable_iterator'>
<callable_iterator object at 0x10545ec88>
[email protected]
[email protected]
[email protected]
<class 'list'>
['[email protected]', '[email protected]', '[email protected]']

由结果可知:finditer 得到的是可迭代对象,finfdall 得到的是一个列表。

示例二:

import recontent = '''email:[email protected]:[email protected]:[email protected]'''pattern = re.compile(r'(?P<number>\d+)@(?P<mail_type>\w+).com')result_finditer = re.finditer(pattern, content)print(type(result_finditer))print(result_finditer)iter_dict = {} # 把最后得到的结果for i in result_finditer: print('邮箱号码是:', i.group(1),'邮箱类型是:',i.group(2)) number = i.group(1) mail_type = i.group(2) iter_dict.setdefault(number, mail_type) # 使用 dict.setdefault 创建了一个字典print(iter_dict)print('+++++++++++++++++++++++++++++++')result_findall = re.findall(pattern, content)print(result_findall)print(type(result_findall))

输出结果:

<class 'callable_iterator'>
<callable_iterator object at 0x104c5cbe0>
邮箱号码是: 123456 邮箱类型是: 163
邮箱号码是: 234567 邮箱类型是: 163
邮箱号码是: 345678 邮箱类型是: 163
{'123456': '163', '234567': '163', '345678': '163'}
+++++++++++++++++++++++++++++++
[('123456', '163'), ('234567', '163'), ('345678', '163')]
<class 'list'>

finditer 得到的可迭代对象 i,也可以使用 lastindex,lastgroup 方法。

print('lastgroup 最后一个被捕获的分组的名字',i.lastgroup)

findall 当正则没有分组,返回就是正则匹配。

re.findall(r"\d+@\w+.com", content)['[email protected]', '[email protected]', '[email protected]']

有一个分组返回的是分组的匹配

re.findall(r"(\d+)@\w+.com", content)['2345678', '2345678', '345678']

多个分组时,将结果作为 元组,一并存入到 列表中。

re.findall(r"(\d+)@(\w+).com", content)[('2345678', '163'), ('2345678', '163'), ('345678', '163')]

PS:这里再为大家提供2款非常方便的正则表达式工具供大家参考使用:

JavaScript正则表达式在线测试工具:
http://tools..net.cn/regex/javascript

正则表达式在线生成工具:
http://tools..net.cn/regex/create_reg

更多关于Python相关内容可查看本站专题:《Python正则表达式用法总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总》

希望本文所述对大家Python程序设计有所帮助。


  • 上一条:
    python 实时得到cpu和内存的使用情况方法
    下一条:
    对python程序内存泄漏调试的记录
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • 在python语言中Flask框架的学习及简单功能示例(0个评论)
    • 在Python语言中实现GUI全屏倒计时代码示例(0个评论)
    • Python + zipfile库实现zip文件解压自动化脚本示例(0个评论)
    • python爬虫BeautifulSoup快速抓取网站图片(1个评论)
    • vscode 配置 python3开发环境的方法(0个评论)
    • 近期文章
    • 在windows10中升级go版本至1.24后LiteIDE的Ctrl+左击无法跳转问题解决方案(0个评论)
    • 智能合约Solidity学习CryptoZombie第四课:僵尸作战系统(0个评论)
    • 智能合约Solidity学习CryptoZombie第三课:组建僵尸军队(高级Solidity理论)(0个评论)
    • 智能合约Solidity学习CryptoZombie第二课:让你的僵尸猎食(0个评论)
    • 智能合约Solidity学习CryptoZombie第一课:生成一只你的僵尸(0个评论)
    • 在go中实现一个常用的先进先出的缓存淘汰算法示例代码(0个评论)
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(95个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-10
    • 2016-11
    • 2018-04
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2022-01
    • 2023-07
    • 2023-10
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客