python正则表达式最详解
作者:(∪.∪ )...zzz 发布时间:2022-03-13 07:29:47
标签:python,正则表达式,详解
一、正则表达式–元字符
re 模块使 Python 语言拥有全部的正则表达式功能
1. 数量词
# 提取大小写字母混合的单词
import re
a = 'Excel 12345Word23456PPT12Lr'
r = re.findall('[a-zA-Z]{3,5}',a)
# 提取字母的数量3个到5个
print(r)
# ['Excel', 'Word', 'PPT']
# 贪婪 与 非贪婪 【Python默认使用贪婪模式】
# 贪婪:'[a-zA-Z]{3,5}'
# 非贪婪:'[a-zA-Z]{3,5}?' 或 '[a-zA-Z]{3}'
# 建议使用后者,不要使用?号,否则你会与下面的?号混淆
# 匹配0次或无限多次 *号,*号前面的字符出现0次或无限次
import re
a = 'exce0excell3excel3'
r = re.findall('excel*',a)
r = re.findall('excel.*',a) # ['excell3excel3']
# excel 没有l 有很多l都可以匹配出来
print(r)
# ['exce', 'excell', 'excel']
# 匹配1次或者无限多次 +号,+号前面的字符至少出现1次
import re
a = 'exce0excell3excel3'
r = re.findall('excel+',a)
print(r)
# ['excell', 'excel']
# 匹配0次或1次 ?号,?号经常用来去重复
import re
a = 'exce0excell3excel3'
r = re.findall('excel?',a)
print(r)
# ['exce', 'excel', 'excel']
2. 字符匹配
line = 'xyz,xcz.xfc.xdz,xaz,xez,xec'
r = re.findall('x[de]z', line)
# pattern 是x开始,z结束,含d或e
print(r)
# ['xdz', 'xez']
r = re.findall('x[^de]z', line)
# pattern 是x开始,z结束,不是含d或e
print(r)
# ['xyz', 'xcz', 'xaz']
# \w 可以提取中文,英文,数字和下划线,不能提取特殊字符
import re
a = 'Excel 12345Word\n23456_PPT12lr'
r = re.findall('\w',a)
print(r)
# ['E', 'x', 'c', 'e', 'l', '1', '2', '3', '4', '5', 'W', 'o', 'r', 'd', '2', '3', '4', '5', '6', '_', 'P', 'P', 'T', '1', '2', 'l', 'r']
# \W 提取特殊字符,空格 \n \t
import re
a = 'Excel 12345Word\n23456_PPT12lr'
r = re.findall('\W',a)
print(r)
# [' ', '\n']
3. 边界匹配
# 限制电话号码的位置必需是8-11位才能提取
import re
tel = '13811115888'
r = re.findall('^\d{8,11}$',tel)
print(r)
# ['13811115888']
4. 组
# 将abc打成一个组,{2}指的是重复几次,匹配abcabc
import re
a = 'abcabcabcxyzabcabcxyzabc'
r = re.findall('(abc){2}',a) # 与
# ['abc', 'abc']
print(r)
r = re.findall('(abc){3}',a)
# ['abc']
5. 匹配模式参数
# findall第三参数 re.I忽略大小写
import re
a = 'abcFBIabcCIAabc'
r = re.findall('fbi',a,re.I)
print(r)
# ['FBI']
# 多个模式之间用 | 连接在一起
import re
a = 'abcFBI\nabcCIAabc'
r = re.findall('fbi.{1}',a,re.I | re.S)
# 匹配fbi然后匹配任意一个字符包括\n
print(r)
# ['FBI\n']
二、方法
re.findall
匹配出字符串中所有 与制定值相关的值
以列表的形式返回
未匹配则返回空列表
import re
re.findall(pattern, string, flags=0)
pattern.findall(string[ , pos[ , endpos]])
import re
line = "111aaabbb222小呼噜奥利奥"
r = re.findall('[0-9]',line)
print(r)
# ['1', '1', '1', '2', '2', '2']
re.match
re.match 尝试从字符串的起始位置匹配一个模式
如果不是起始位置匹配成功的话,match()就返回none。
re.match(pattern, string, flags=0)
# (标准,要匹配的,标志位)
print(re.match('www','www.xxxx.com'))
print(re.match('www','www.xxxx.com').span())
print(re.match('com','www.xxxx.com'))
<re.Match object; span=(0, 3), match='www'>
(0, 3)
None
group匹配对象
import re
a = 'life is short,i use python,i love python'
r = re.search('life(.*)python(.*)python',a)
print(r.group(0)) # 完整正则匹配 ,life is short,i use python,i love python
print(r.group(1)) # 第1个分组之间的取值 is short,i use
print(r.group(2)) # 第2个分组之间的取值 ,i love
print(r.group(0,1,2)) # 以元组形式返回3个结果取值 ('life is short,i use python,i love python', ' is short,i use ', ',i love ')
print(r.groups()) # 返回就是group(1)和group(2) (' is short,i use ', ',i love ')
import re
# .* 表示任意匹配除换行符(\n、\r)之外的任何单个或多个字符
# (.*?) 表示"非贪婪"模式,只保存第一个匹配到的子串
# re.M 多行匹配,影响 ^ 和 $
# re.I 使匹配对大小写不敏感
line = "Cats are smarter than dogs"
matchObj1 = re.match(r'(.*) are (.*?) .*', line, re.M|re.I)
matchObj2 = re.match(r'(.*) smarter (.*?) .*', line, re.M|re.I)
matchObj3 = re.match(r'(.*) than (.*)', line, re.M|re.I)
print(matchObj1)
print(matchObj2)
print(matchObj3)
# <re.Match object; span=(0, 26), match='Cats are smarter than dogs'>
# <re.Match object; span=(0, 26), match='Cats are smarter than dogs'>
# None
if matchObj1:
print ("matchObj1.group() : ", matchObj1.group())
print ("matchObj1.group(1) : ", matchObj1.group(1))
print ("matchObj1.group(2) : ", matchObj1.group(2))
else:
print ("No match!!")
if matchObj2:
print ("matchObj2.group() : ", matchObj2.group())
print ("matchObj2.group(1) : ", matchObj2.group(1))
print ("matchObj2.group(2) : ", matchObj2.group(2))
else:
print ("No match!!")
if matchObj3:
print ("matchObj3.group() : ", matchObj3.group())
print ("matchObj3.group(1) : ", matchObj3.group(1))
print ("matchObj3.group(2) : ", matchObj3.group(2))
else:
print ("No match!!")
# matchObj1.group() : Cats are smarter than dogs
# matchObj1.group(1) : Cats
# matchObj1.group(2) : smarter
# matchObj2.group() : Cats are smarter than dogs
# matchObj2.group(1) : Cats are
# matchObj2.group(2) : than
# matchObj3.group() : Cats are smarter than dogs
# matchObj3.group(1) : Cats are smarter
# matchObj3.group(2) : dogs
import re
# 点 是匹配单个字符
# 星是前面的东西出现0次或无数次
# 点星就是任意字符出现0次或无数次
str = "a b a b"
matchObj1 = re.match(r'a(.*)b', str, re.M|re.I)
matchObj2 = re.match(r'a(.*?)b', str, re.M|re.I)
print("matchObj1.group() : ", matchObj1.group())
print("matchObj2.group() : ", matchObj2.group())
# matchObj1.group() : a b a b
# matchObj2.group() : a b
re.search
扫描整个字符串并返回第一个成功的匹配。
re.search(pattern, string, flags=0)
import re
line = "cats are smarter than dogs"
matchObj = re.match(r'dogs',line,re.M|re.I)
matchObj1= re.search(r'dogs',line,re.M|re.I)
matchObj2= re.match(r'(.*) dogs',line,re.M|re.I)
if matchObj:
print ("match --> matchObj.group() : ", matchObj.group())
else:
print ("No match!!")
if matchObj1:
print ("match --> matchObj1.group() : ", matchObj1.group())
else:
print ("No match!!")
if matchObj2:
print ("match --> matchObj2.group() : ", matchObj2.group())
else:
print ("No match!!")
# No match!!
# match --> matchObj1.group() : dogs
# match --> matchObj2.group() : cats are smarter than dogs
re.compile
re.compile是将正则表达式转换为模式对象
这样可以更有效率匹配。使用compile转换一次之后,以后每次使用模式时就不用进行转换
三、检索和替换
re.sub 替换字符串
re.sub('被替换的','替换成的',a)
# 把FBI替换成BBQ
import re
a = 'abcFBIabcCIAabc'
r = re.sub('FBI','BBQ',a)
print(r)
# 把FBI替换成BBQ,第4参数写1,证明只替换第一次,默认是0(无限替换)
import re
a = 'abcFBIabcFBIaFBICIAabc'
r = re.sub('FBI','BBQ',a,1)
print(r)
# abcBBQabcCIAabc
# abcBBQabcFBIaFBICIAabc
# 把函数当参数传到sub的列表里,实现把业务交给函数去处理,例如将FBI替换成$FBI$
import re
a = 'abcFBIabcFBIaFBICIAabc'
def 函数名(形参):
分段获取 = 形参.group() # group()在正则表达式中用于获取分段截获的字符串,获取到FBI
return '$' + 分段获取 + '$'
r = re.sub('FBI',函数名,a)
print(r)
来源:https://blog.csdn.net/grb819/article/details/121067700
0
投稿
猜你喜欢
- 先给大家介绍下Python读取文件夹按数字排序的代码,内容如下所示:python中 os.listdir()方法用于返回指定的文件夹包含的文
- 介绍PaddleOCR 是一个基于百度飞桨的OCR工具库,包含总模型仅8.6M的超轻量级中文OCR,单模型支持中英文数字组合识别、
- Douglas Crockford是JavaScript开发社区最知名的权威,是JSON、JSLint、JSMin和ADSafe之父,是《J
- 曾经为看别人写的杂乱代码而头痛吗?曾经为看BWindow代码而烦恼吗?曾经为减小JS体积和JS的可读性之间的矛盾而左右徘徊吗?最好的办法是有
- ExecuteReader(),ExecuteNonQuery(),ExecuteScalar(),ExecuteXmlReader()之间
- 本文实例为大家分享了python绘制雪花的具体代码,供大家参考,具体内容如下代码非常容易理解,画着玩玩还是可以的。直接上代码# -*- co
- Entity Framework 4.0 也可以支持大名鼎鼎的MySql,这篇POST将向展示如何实现EF+MyS
- 如下所示:hist = model.fit(x,y, epochs=epoch_num, batch_size=32,callbacks=e
- 除了IE浏览器,其他所有主流的浏览器均支持原生的 Base64 编码:btoa(text) – base64 encodes text. a
- 需求背景:进行分值计算。如下图,如果只是一两个还好说,写写判断,但是如果有几十个,几百个,会不会惨不忍睹。而且,下面的还是三种情况。例如:解
- 现在很多地方都需要用到关键词过滤功能。比如一般的服务器都不允许一些词出现在网页上,站长有时候会对在本网站发布信息的内容进行一个广告过滤等。雨
- Dreamweaver一直是不少网友钟情的网页设计工具,除了它强大的动态效果制作能力外,方便简洁的操作界面更是独具特色,下面我们将以最新版本
- 本文实例形式讲解了python的类变量和成员变量用法,对于Python程序设计有一定的参考价值。分享给大家供大家参考。具体如下:先看看下面这
- 本文介绍的圆角方法很特别,有创意。昨天群里大家讨论到一个豆瓣上的按钮,下面这个。在这里用到了不同宽度的按钮,但是只是用到了一个图片。&nbs
- 本文实例讲述了php查询mysql数据库并将结果保存到数组的方法。分享给大家供大家参考。具体分析如下:这里主要用到了mysql_fetch_
- 通过《SQL Server 数据库备份和还原认识和总结(一)》,相信您对数据备份和还原有了一个更深入的认识,在上文中我没有对事务日志做剖析,
- 发现一个有意思的现象,labelimg打开图片和xml标签时候,看不到标注好的框框,仔细查看了xml文件,没发现什么异常,后面试一下,才发现
- 匹配中文字符的正则表达式: [\u4e00-\u9fa5]评注:匹配中文还真是个头疼的事,有了这个表达式就好办了匹配双字节字符(包括汉字在内
- 今天是 Firefox3的2008下载日 ,这就意味着Firefox3正式发布了。Firefox3有众多的改进和新功能,我最关注的功能之一是
- 在印刷排版中“point”是一个绝对的单位,它等于 1/72 英寸。可以用尺子丈量的,物理的英寸。但在CSS中pt的含义