正则表达式:是一个文本模式,描述在搜索文本时要匹配的一个或多个字符。
语法=字面值(普通字符+需转义加\)+元字符
作用:数据验证;文本扫面;文本提取;文本替换;文本切割。
需转义的字面值:\ ^ $ . | ? * + () [] {}
贪婪:匹配最大范围结果;非贪婪:匹配最小范围结果;方法:量词后加?
编译“re.compile"实现:将正则表达式编译为字节码并缓存(RegexObject)
import re
s = 'Lily is 24 years old.Ben is 4 years old.'
p1 = re.compile('\d+')
p1.findall(s)
['24', '4']
re.findall('\d+',s)
['24', '4']
pp1 = re.compile('[A-Z]\w+')
pp1.findall(s)
['Lily', 'Ben']
finfall()的用法:查找,返回list
遇到需转义的字面值时,可以加\转义,也可以直接加r
s2 = '\\oanfanfnaanlnf'
p2 = re.compile('\\oa')
抛异常
p2 = re.compile('\\\\oa')
p2.findall(s2)
['\\oa']
p2 = re.compile(r'\\oa')
p2.findall(s2)
['\\oa']
match的用法:查找;返回MatchObject;可以展示详细信息;只从开始的位置开始匹配
search的用法:查找;返回MatchObject;可以展示详细信息;可从任意位置开始匹配
s3 = 'ajfoje7anfjefoao9nalkfn'
p3 = re.compile(r'aj')
p3.match(s3)
<re.Match object; span=(0, 2), match='aj'>
p4 = re.compile(r'fo')
p4.match(s3)
p4.match(s3,2)
<re.Match object; span=(2, 4), match='fo'>
p4.search(s3)
<re.Match object; span=(2, 4), match='fo'>
finditer()的用法:查找,返回包括MatchObject的迭代器
s = 'Lily is 24 years old.Ben is 4 years old.'
p1 = re.compile('\d+')
i = p1.finditer(s)
for m in i:
print(m)
<re.Match object; span=(8, 10), match='24'>
<re.Match object; span=(28, 29), match='4'>
有关分组,用()实现
import re
s = 'anfnoafo93aofajofh89jfan'
p = re.compile(r'\d+')
p.findall(s)
['93', '89']
p1 = re.compile(r'(\d+).*?(\d+)')
p1.search(s)
<re.Match object; span=(8, 20), match='93aofajofh89'>
m = p1.search(s)
m.group(0)
'93aofajofh89'
m.group(1)
'93'
m.group(2)
'89'
m.start(1)
8
m.end(1)
10
分组的一些灵活用法:
re.search(r'ab+c','ababc')
<re.Match object; span=(2, 5), match='abc'>
re.search(r'(ab)+c','ababc')
<re.Match object; span=(0, 5), match='ababc'>
re.search(r'center|re','centre')
<re.Match object; span=(4, 6), match='re'>
re.search(r'cent(re|er)','center')
<re.Match object; span=(0, 6), match='center'>
re.search(r'(\w+)\1','hello world')
<re.Match object; span=(2, 4), match='ll'>
re.search(r'(\w+) \1','hello hello world')
<re.Match object; span=(0, 11), match='hello hello'>
s2 = 'nfanfaoafaojap893ajnfjann93njfaknkank'
p2 = re.compile(r'\d+')
p.split(s)
['anfnoafo', 'aofajofh', 'jfan']
re.split(r'(\W)','hello world')
['hello', ' ', 'world']
re.split(r'\d+',s2,1)
['nfanfaoafaojap', 'ajnfjann93njfaknkank']
s3 = 'GUU9797\nIBI6998\nVUVU69979'
re.sub(r'([A-Z]+)(\d+)','\g<2>-\g<1>',s3)
'9797-GUU\n6998-IBI\n69979-VUVU'
分组可以命名:
m1 = re.search(r'(?P<a>\w+) (?P<b>\w+)','hello world')
m1.group('a')
'hello'
m1.group('b')
'world'
编译笔记(改变正则默认行为):
re.search(r'(\w+) \1','Hello hello world')
re.search(r'(\w+) \1','Hello hello world',re.I)
<re.Match object; span=(0, 11), match='Hello hello'>