这篇文章主要介绍了Python3正则匹配re.split,re.finditer及re.findall函数用法,结合实例形式详细分析了正则匹配re.split,re.finditer及re.findall函数的概念、参数、用法及操作注意事项,需要的朋友可以参考下

 

本文实例讲述了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)
该标志通过给予你更灵活的格式以便你将正则表达式写得更易于理解。

示例:

1
2
3
4
5
6
7
import re
content = '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 指定最大分割次数,不指定将全部分割
1
2
3
4
5
6
7
8
9
import re
str = '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 需要匹配的字符串
1
2
3
4
5
import re
str = '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 返回一个可迭代对象。

示例一:

1
2
3
4
5
6
7
8
9
10
11
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>
123456@163.com
234567@163.com
345678@163.com
<class 'list'>
['123456@163.com', '234567@163.com', '345678@163.com']

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

示例二:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import re
content = '''email:123456@163.com
email:234567@163.com
email:345678@163.com
'''
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 当正则没有分组,返回就是正则匹配。

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

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

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

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

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

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

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

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

原文链接:https://blog.csdn.net/cityzenoldwang/article/details/78398406

Python3正则匹配re.split,re.finditer及re.findall函数用法详解的更多相关文章

  1. Python3中正则模块re.compile、re.match及re.search函数用法详解

    Python3中正则模块re.compile.re.match及re.search函数用法 re模块 re.compile.re.match. re.search 正则匹配的时候,第一个字符是 r,表 ...

  2. C#的String.Split 分割字符串用法详解的代码

    代码期间,把代码过程经常用的内容做个珍藏,下边代码是关于C#的String.Split 分割字符串用法详解的代码,应该对码农们有些用途. 1) public string[] Split(params ...

  3. python3 正则匹配[^abc]和(?!abc)的区别(把多个字符作为一个整体匹配排除)

    目的:把数字后面不为abc的字符串找出来 如1ab符合要求,2abc不符合要求 str = '1ab' out = re.match(r'\d+(?!abc)',str) str1 = '1abc' ...

  4. OpenCV模板匹配函数matchTemplate详解

    参考文档:http://www.opencv.org.cn/opencvdoc/2.3.2/html/doc/tutorials/imgproc/histograms/template_matchin ...

  5. python3字典:获取json响应值来进行断言的用法详解

    在Python中我们做接口经常用到一些json的返回值我们常把他转化为字典,在前面的python数据类型详解(全面)中已经谈到对字典的的一些操作,今天我们就获取json返回值之后,然后转化为字典后的获 ...

  6. JS中正则匹配的三个方法match exec test的用法

    javascript中正则匹配有3个方法,match,exec,test: match是字符串的一个方法,接收一个RegExp对象做为参数: match() 方法可在字符串内检索指定的值,或找到一个或 ...

  7. python3中列表、元组、字典的增删改查说明详解

    python基础中的列表.元组.字典属于python中内置的序列数据结构.其中序列可以进行的操作包括索引.截取(切片).加.乘.成员检查等. 1.列表 列表(list)是最常用的python数据类型之 ...

  8. sql语句中like匹配的用法详解

    在SQL结构化查询语言中,LIKE语句有着至关重要的作用. LIKE语句的语法格式是:select * from 表名 where 字段名 like 对应值(子串),它主要是针对字符型字段的,它的作用 ...

  9. Linux split命令参数及用法详解---linux分割文件命令

    转载自:http://blog.csdn.net/xiaoshunzi111/article/details/52173994 功能说明:分割文件. Split:按指定的行数截断文件 格式: spli ...

随机推荐

  1. 必须要注意的 C++ 动态内存资源管理(六)——vector的简单实现

    必须要注意的 C++ 动态内存资源管理(六)——vector的简单实现 十六.myVector分析         我们知道,vector类将其元素存放在连续的内存中.为了获得可接受的性能,vetor ...

  2. Learning Face Age Progression: A Pyramid Architecture of GANs-1-实现人脸老化

    Learning Face Age Progression: A Pyramid Architecture of GANs Abstract 人脸年龄发展有着两个重要的需求,即老化准确性和身份持久性, ...

  3. java.io.IOException: Input is binary and unsupported

    十一月 16, 2019 11:49:47 上午 org.apache.catalina.core.StandardWrapperValve invoke严重: Servlet.service() f ...

  4. LeetCode:第K个排列【60】

    LeetCode:第K个排列[60] 题目描述 给出集合 [1,2,3,…,n],其所有元素共有 n! 种排列. 按大小顺序列出所有排列情况,并一一标记,当 n = 3 时, 所有排列如下: &quo ...

  5. 并行执行任务 Stat-Job

    最近在写一些powershell脚本时候遇到一个问题,那就是要解压十几个zip文件,这样仅执行完解压操作差不多5min的时间就过去了,严重影响了效率,这时就想到了使用多线程的方法来执行这个解压操作,经 ...

  6. 【电商日志项目之四】数据清洗-ETL

    环境 hadoop-2.6.5 首先要知道为什么要做数据清洗?通过各个渠道收集到的数据并不能直接用于下一步的分析,所以需要对这些数据进行缺失值清洗.格式内容清洗.逻辑错误清洗.非需求数据清洗.关联性验 ...

  7. UE4 ios环境搭建备忘

    1.windows.mac安装证书 2.安装xcode .app -- 路径可以拖入 sudo gem install xcodeproj 3.错误处理 Setting up Mono Running ...

  8. Neo4j CQL基本使用

    Neo4j用CQL作为查询语言 CQL  Neo4j图形数据库的查询语言 是一种声明性模式匹配语言 遵循SQL语法 语法是非常简单且人性化.可读的格式 1.启动服务,打开浏览器 在数据浏览器中的美元提 ...

  9. QT实现支持加密的Sqlite数据库引擎

    Sqlite数据库使用很广泛,我们经常会在发布一些小型软件的时候使用它,因为它不需要安装服务器.QT默认的数据库引擎是支持SQLITE数据库的,但并不支持对数据库加密,不加密的Sqlite数据库任何人 ...

  10. !与&&优先级的问题

    逻辑否(!)是一元操作符,逻辑与(&&)是二元操作符,一元操作符的优先级高于任何二元操作符. 例如: bool flag:int t: if(!flag && t &g ...