正则表达式

本文深入讲解了Python中的正则表达式,包括模块导入、基本操作如split和match,以及高级功能如findall、finditer和sub的使用实例。通过实例演示如何匹配、替换和拆分字符串,以及如何利用正则表达式进行电话号码提取和文本处理。
摘要由CSDN通过智能技术生成
import re   #导入模块re对字符串应用正则表达式,它包括模式匹配,替换,拆分
text = "apple banana\t is \tmyfavorite"
print(text)
apple banana	 is 	myfavorite
re.split('\s+',text)
['apple', 'banana', 'is', 'myfavorite']
regex = re.compile('\s+')
regex.findall(text)
[' ', '\t ', ' \t']

re.match() 从字符串开头匹配文本,返回匹配对象
re.match(pattern, string, flags=0)
pattern 匹配的正则表达式
string 要匹配的字符串。
flags 标志位,用于控制正则表达式的匹配方式,如:是否区分大小写,多行匹配等等。

import re
print(re.match('www', 'www.runoob.com').span())  # 在起始位置匹配   sapn()返回匹配值的下标【(0,3)左闭右开】,若字符串开始不符合正则表达式,则匹配失败span()输出有错误
print(re.match('www', 'www.runoob.com'))         #返回的是匹配对象      
print(re.match('com','www.runoob.com'))          # 不在起始位置匹配,返回的是None
(0, 3)
<re.Match object; span=(0, 3), match='www'>
None

re.search()扫描整个字符串并返回第一个成功的匹配
re.search(pattern, string, flags=0)

import re
 
print(re.search('www', 'roon,www.runoob.com.www').span()) #可以扫描整个字符串,只返回第一个匹配成功的字符串位置      
print(re.search('www', 'www.runoob.com.www').span())      # 在起始位置匹配
print(re.search('com', 'www.runoob.com').span())          # 不在起始位置匹配,都返回
                                                          
(5, 8)
(0, 3)
(11, 14)
import re
 
line = "Cats are smarter than dogs"
#. .* 就是单个字符(除\r\n外)匹配任意次,即贪婪匹配
# (.*?) 表示"非贪婪"模式,满足.*条件的情况只匹配一次,即最小匹配.
matchObj = re.search( r'(.*?) smarter (.*) (.*)', line, re.M|re.I)  #正则式中用()表示的就是要提取的分组group,此例中就定义了两个组
 
if matchObj:
    print ("matchObj.group() : ", matchObj.group())    #group()或group(0)表示匹配到的原始字符串
    print ("matchObj.group(0) : ", matchObj.group(0))
    print ("matchObj.groups() : ", matchObj.groups())  #返回一个包含所有小组字符串的元组
    print ("matchObj.group(1) : ", matchObj.group(1))  #group(1)表示第一个字串(也就是正则式中第一个括号匹配到的内容)
    print ("matchObj.group(2) : ", matchObj.group(2))  #group(2)表示第二个子串(第二个括号匹配到的内容)
    print ("matchObj.group(3) : ", matchObj.group(3))
else:
    print ("No match!!")
matchObj.group() :  Cats are smarter than dogs
matchObj.group(0) :  Cats are smarter than dogs
matchObj.groups() :  ('Cats are', 'than', 'dogs')
matchObj.group(1) :  Cats are
matchObj.group(2) :  than
matchObj.group(3) :  dogs

re.sub()替换字符串中的匹配项

re.sub(正则中的模式字符串,替换的字符串,原始字符串,模式匹配后替换的最大次数)
import re
 
phone = "2004-959-559 # 这是一个电话号码"
 
# 删除注释
num = re.sub(r'#.*$', "", phone)
print ("电话号码 : ", num)
 
# 移除非数字的内容
num = re.sub(r'\D', " ", phone)
print ("电话号码 : ", num)
电话号码 :  2004-959-559 
电话号码 :  2004 959 559           

re.subn()函数返回替换次数。

格式:subn(pattern, repl, string, count=0, flags=0);

解释:用A替换123中的1,结果为A23,repl就是指的A。把所有的数字替换为A:

text = 'The moment you think about giving up, think of the reason why you held on so long.'
itext = re.finditer(r'\bt\w*',text)
for i in itext:
    print(i.group())
#2.用空格分割句子
print(re.split(r' ',text))
#3.用‘-’代替句子中的空格 
print(re.sub(' ','-',text))
#4.用‘-’代替句子中的空格,并返回替换次数
print(re.subn(' ','-',text))
#********** End **********#
think
think
the
['The', 'moment', 'you', 'think', 'about', 'giving', 'up,', 'think', 'of', 'the', 'reason', 'why', 'you', 'held', 'on', 'so', 'long.']
The-moment-you-think-about-giving-up,-think-of-the-reason-why-you-held-on-so-long.
('The-moment-you-think-about-giving-up,-think-of-the-reason-why-you-held-on-so-long.', 16)

compile()用于编译正则表达式,生成一个正则表达式(pattern)对象,供match()和search()使用

import re
pattern = re.compile(r'\d+')                    # 用于匹配至少一个数字
m = pattern.match('one12twothree34four')        # 查找头部,没有匹配
print(m)
n = pattern.search('onetwo4fpur56')
print(n)
print(n.span())    #返回匹配成功的索引
n.group(0)         #返回匹配成功的整个字串
None
<re.Match object; span=(6, 7), match='4'>
(6, 7)





'4'
import re
pattern = re.compile(r'([a-z])([a-z]+)([a-z]+)', re.I)   # re.I 表示忽略大小写, ()()()将匹配到的字符串分成三组 
                                                         # + 加号表示他前面的表达式尽可能的多匹配
m = pattern.match('Hello World Wide Web')
print( m )                                               # 匹配成功,返回一个 Match 对象
<re.Match object; span=(0, 5), match='Hello'>
m.group(0)                            # 返回匹配成功的整个子串   以空格匹配间断
'Hello'
m.span(0)                             # 返回匹配成功的整个子串的索引
(0, 5)
m.group(1)                            # 返回第一个分组匹配成功的子串
'H'
m.span(1)                             # 返回第一个分组匹配成功的子串的索引
(0, 1)
m.group(2)                            # 返回第二个分组匹配成功的子串(第二个()有+,尽可能多的匹配)
'ell'
m.span(2)                             # 返回第二个分组匹配成功的子串索引
(1, 4)
m.groups()                            # 等价于 (m.group(1), m.group(2), ...)
('H', 'ell', 'o')
m.group(3)                            # 存在第三个分组
'o'
m.group(4)                            #因为前面只有三个(),不存在地四个分组
---------------------------------------------------------------------------

IndexError                                Traceback (most recent call last)

<ipython-input-140-809a6fc4f3f9> in <module>
----> 1 m.group(4)


IndexError: no such group

findall() 【re.findall() / pattern.findall(待匹配字符串,指定字符串起始位置,指定字符串结束位置)】
在字符串中找到正则表达式所匹配的所有子串,并返回一个列表;
如果有多个匹配模式,则返回元组列表,如果没有找到匹配的,则返回空列表。

注意: match 和 search 是匹配一次 findall 匹配所有。

import re
 
result1 = re.findall(r'\d+','runoob 123 google 456')
pattern = re.compile(r'\d+')   # 查找数字
result2 = pattern.findall('runoob 123 google 456')
result3 = pattern.findall('run88oob123google456', 0, 10)
 
print(result1)
print(result2)
print(result3)
['123', '456']
['123', '456']
['88', '12']

re.finditer() 迭代返回所有子串
re.finditer(匹配的正则表达式,要匹配的字符串)

import re 
it = re.finditer(r"\d+","12a32bc43jf3") 
for i in it: 
    print (i.group() )
12
32
43
3

re.split() 按照匹配规则将字符串分割返回列表
re.split(正则表达式, 要匹配的字符串,分割次数,标志位)

import re
re.split('\W+', 'runoob, runoob, runoob.')   # \w匹配非数字字母下划线
['runoob', 'runoob', 'runoob', '']
re.split('(\W+)', ' runoob, runoob, runoob.') 

['', ' ', 'runoob', ', ', 'runoob', ', ', 'runoob', '.', '']
re.split('\W+', ' runoob, runoob, runoob.', 1) 

['', 'runoob, runoob, runoob.']
re.split('a*', 'hello world')   # 对于一个找不到匹配的字符串而言,split 不会对其作出分割

['', 'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', '']

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

酸菜鱼的精神世界

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值