因为字符串处理无所不在,正则毫无疑问是最简洁和高效的处理方法。今天我们要来一起梳理的知识点就是Python正则表达式。本文将用十个Python正则表达式的例子,帮助初学者入门Python正则表达式,下面一起来看看吧~
1、查找第一个匹配串
s = 'i love python very much'
pat = 'python'
r = re.search(pat,s)
print(r.span()) #(7,13)
2、查找所有1
s = '山东省潍坊市青州第1中学高三1班'
pat = '1'
r = re.finditer(pat,s)
for i in r:
print(i)
# <re.Match object; span=(9,10),match='1'>
# <re.Match object; span=(14,15),match='1'>
3、d匹配数字[0-9]
s = '一共20行代码运行时间13.59s'
pat = r'd+' # +表示匹配数字(d表示数字的通用字符)1次或多次
r = re.findall(pat,s)
print(r)
# ['20','13','59']
4、表示前一个字符匹配0或1次
s = '一共20行代码运行时间13.59s'
pat = r'd+.?d+' # ?表示匹配小数点(.)0次或1次
r = re.findall(pat,s)
print(r)
# ['20','13.59']
5、^匹配字符串的开头
s = 'This module provides regular expression matching operations similar to those found in Perl'
pat = r'^[emrt]' # 查找以
r = re.findall(pat,s)
print(r)
# [],因为字符串的开头是字符`T`,不在emrt匹配范围内,所以返回为空
6、re.I 忽略大小写
s = 'This module provides regular expression matching operations similar to those found in Perl'
pat = r'^[emrt]' # 查找以
r = re.compile(pat,re.I).search(s)
print(r)
# <re.Match object; span=(0,1),match='T'> 表明字符串的开头在匹配列表中
7、使用正则提取单词
s = 'This module provides regular expression matching operations similar to those found in Perl'
pat = r's[a-zA-Z]+'
r = re.findall(pat,s)
print(r) #[' module',' provides',' regular',' expression',' matching',' operations',' similar',' to',' those',' found',' in',' Perl']
8、只捕获单词,去掉空格
s = 'This module provides regular expression matching operations similar to those found in Perl'
pat = r's([a-zA-Z]+)'
r = re.findall(pat,s)
print(r) #['module','provides','regular','expression','matching','operations','similar','to','those','found','in','Perl']
9、补充上第一个单词
s = 'This module provides regular expression matching operations similar to those found in Perl'
pat = r's?([a-zA-Z]+)'
r = re.findall(pat,s)
print(r) #['This','module','provides','regular','expression','matching','operations','similar','to','those','found','in','Perl']
10、使用split函数直接分割单词
使用以上方法分割单词,不是简洁的,仅仅为了演示。分割单词最简单还是使用 split 函数。
s = 'This module provides regular expression matching operations similar to those found in Perl'
pat = r's+'
r = re.split(pat,s)
print(r) # ['This','module','provides','regular','expression','matching','operations','similar','to','those','found','in','Perl']
以上就是Python正则表达式的例子讲解,大家都看懂了吗?如果还想学习更多关于Python的知识点,可以看看资讯Python栏目的往期内容,海量的学习干货等着你~