正则表达式是由一些具有特殊含义的字符组成的字符串,多用于查找、替换符合规则的字符串。在数据验证、文本扫描、文本提取、文本替换、文本分割等处都会经常用到。
1.语法(元字符、普通字符、需转义字符)
a. 元字符
元字符 | 含义 |
---|---|
. | 除\n外的所有字符 |
\d | 数字,等同0-9 |
\D | 非数字,^0-9 |
\s | 空白字符 \t\n\r\f\v |
\S | 非空白字符 |
\w | 字母数字字符[a-z A-Z 0-9 _] |
\W | 非字母数字字符 |
^ | 匹配字符串的开始(在集合字符里[^a]表示非(不匹配)的意思 |
$ | 匹配字符串的结束 |
[^x] | 匹配除了x以外的任意字符 |
[^aeiou] | 匹配除了aeiou这几个字母以外的任意字符 |
\B | 匹配不是单词开头或结束的位置 |
\b | 匹配单词的开始或结束 |
(1). 匹配任何任意字符 例如 . 可以匹配 1,n,*,+,- ,等
(2)\d\w\s 匹配第一个字符为数字,第二个字符为字母或数字、或下划线或汉字,第三字符为空格的字符串 例如:11 ,2a , 1_
(3)^\d\d\d$ 匹配三个全部都为数字的字符串 例如: 123,456,789
还可以用于验证输入的字符串是否符合qq(身份证号)的验证 :
例如:^\d{8}$ 匹配8位数字的qq号,^\d{15}&匹配15位均为数字的身份证号
(4)\bOlive\b 匹配单词Olive 例如: I Love Oliver and Olive .这个时候返回的是Olive 而不是Oliver,因为\b....\b返回的匹配的单词
b. 转义字符
\ ^ $ . | ? * +
例如: 需要匹配qq邮箱 \d{8,}+qq+.+com 在这里的. 就需要加斜杠
c. 量词(限定字符)
量词 | 含义 |
---|---|
? | 0或1次 |
* | 0或多次 |
+ | 1或多次 |
+ {n} | 重复n次 |
{n,} | 重复n次或更多次 |
{n,m} | 重复n到m次 |
{,m} | 至多重复m次 |
(1)\d* 匹配重复0次或多次数字 例如:可能为空 或 任意数字 (2,3。。。。)
(2)\d+ 匹配重复1次或多次数字 例如:可能为1个或多个数字 1,23,234,2345,........
(3)\d? 匹配重复次个或者一次数字 例如:可能为空或者任意的一个数字(1,2,。。。)
(4)\d{8}匹配重复8次数字 例如:123456768
(5)\d{4,}匹配重复至少4次数字 例如:1234,12345,124244,。。。。。
(6)^\d{8,11}$ 匹配重复8-11次数字 例如:12345678,123456789,1234567890,12345678901
2. 字符分支和字符备选
a. 字符分支(批量备选)
字符分枝多用于满足不同情况的选择,用“|”将不同的条件分割开来,比如有些固定电话区号有三位,有些有四位,这个时候可以采用字符分枝
例如:\d{3}-\d{8}|\d{4}-\d{8} 可以匹配两种不同长度区号的固定电话
b. 字符分组(Group)或(?< name >exp)
字符分组多用于将多个字符重复,主要通过使用小括号()来进行分组
例:(\d\w){3} 重复匹配3次(\d\w)
应用场景:从匹配模式中提取信息、创建子正则以应用量词
限制备选项范围、重用正则模式中提取的内容
///创建子正则以应用量词
re.search(r'(ab)+c','ababc')
<re.Match object; span=(0, 5), match='ababc'>;
///限制备选项范围
re.search(r'Cent(er|re)','Centre')
<re.Match object; span=(0, 6), match='Centre'>
///分组命名
pattern=re.compile(r'(?P<name>\w+):(?P<score>\d+)')
m=pattern.search(text)
m.group()
'Tom:90'
m.group('name')
'Tom'
3. 贪婪和非贪婪
贪婪匹配:正则表达式中包含重复的限定符时,通常的行为是匹配尽可能多的字符。
懒惰匹配,有时候需要匹配尽可能少的字符。
例如: a.*b,它将会匹配最长的以a开始,以b结束的字符串。如果用它来搜索ababab的话,它会匹配整个字符串ababab。但是我们此时可能需要匹配的是ab这样的话就需要用到懒惰匹配了。懒惰匹配会匹配尽可能少的字符。
用法:量词?
re.findall(r'a.*?b','ababab')
['ab', 'ab', 'ab']
二、. re模块
- 常用函数
名称 | 作用 |
---|---|
P=re.compile(’\d+’) | 编译 |
re.findall (模式,字符串) 或P.findall(字符串) | 查找所有非重叠的匹配项,返回list |
re.match(模式,字符串) | 匹配,仅从起始位置,返回 MatchObjext |
re.search(模式,字符串) | ,任意位置搜索,返回 MatchObjext |
re.finditer((模式,字符串) ) | 查找所有匹配项,返回包含MatchObject元素的迭代器 |
txt='Tom is 8 years old. Mike is 35 years old. Peter is\n +68 years old'
需要多次使用这个模式,用re.compile
pattern=re.compile('\d+')
pattern.findall(txt)
['8', '35', '68']
/// 暂时使用
re.findall('\d+',txt)
['8', '35', '68']
///若起始位置不是要匹配的内容,则返回空
pattern=re.compile(r'<html>')
text='<html><head></html>'
pattern.match(text)
<re.Match object; span=(0, 6), match='<html>'>
以第一个字符位置为起始位置开始匹配
pattern.match(text,1)
<re.Match object; span=(1, 7), match='<html>'>
///re.search
p1=re.compile(r'\d+')
p1.search(txt)
<re.Match object; span=(7, 8), match='8'>
///re.finditer
it = p1.finditer(txt)
for i in it:
print(i)
<re.Match object; span=(7, 8), match='8'>
<re.Match object; span=(28, 30), match='35'>
<re.Match object; span=(53, 55), match='68'>
- 正则匹配对象
函数 | 功能 |
---|---|
.group() | 参数为0或空返回整个匹配,有参时返回特定的分组匹配(如.group(下标)或.group(name)) |
.groups() | 返回包含所有的子分组的元组 |
.start() | 返回特定分组的起始索引 |
.end() | 返回特定分组的终止索引 |
.span() | 返回特定分组的起止索引元组 |
.groupdict() | 以字典形式返回分组名及结果 |
txt='Tom is 8 years old. Mike is 35 years old.'
#(\d+)表示把第一组数字作为一个分组
p1=re.compile(r'(\d+).*?(\d+)')
m=p1.search(txt)
m
<re.Match object; span=(7, 30), match='8 years old. Mike is 35'>
m.group()
'8 years old. Mike is 35'
m.group(0)
'8 years old. Mike is 35'
m.group(1)
'8'
m.group(2)
'35'
m.start(1)
7
m.end(1)
8
m.groups()
('8', '35')
pattern=re.compile(r'(?P<name>\w+):(?P<score>\d+)')
m=pattern.search(text)
m.group()
'Tom:90'
m.group('name')
'Tom'
3. 应用
a.字符串操作
函数 | 功能 |
---|---|
.spilt(以什么分割,要分割的内容) | 分割字符串 |
.sub(旧内容,新内容,要替换的字符串) | 替换字符串 |
.subn(旧内容,新内容,要替换的字符串) | 替换字符串,并返回替换数量 |
///分割
re.split(r'\W','Good Morning')
['Good', 'Morning']
///替换
text='Beautiful is *better* than ugly'
# 不取名称替换
re.sub(r'\*(.*?)\*','<strong\g<1></strong>',text)
'Beautiful is <strong>better</strong> than ugly'
# 取名称替换
re.sub(r'\*(?P<html>.*?)\*','<strong>\g<html></strong>',text)
'Beautiful is <strong>better</strong> than ugly'
ords
'ORD001\nORD002\nORD003\n'
re.sub(r'([A-Z]+)(\d+)','\g<2>-\g<1>',ords)
'001-ORD\n002-ORD\n003-ORD\n'
ords='ORD001\nORD002\nORD003\n'
re.subn(r'([A-Z]+)(\d+)','\g<2>-\g<1>',ords)
('001-ORD\n002-ORD\n003-ORD\n', 3)
b. 编译标记
名称 | 作用 |
---|---|
re.I | 忽略大小写 |
re.M | 匹配多行 |
re.S | 指定"."匹配所有字符,包括\n |
text='Python python PYThon'
re.findall('python',text)
['python']
re.findall('python',text,re.I)
['Python', 'python', 'PYThon']
re.findall(r'^<html>','\n<html>')
[]
re.findall(r'^<html>','\n<html>',re.M)
['<html>']
re.findall(r'\d(.)','1\ne')
[]
re.findall(r'.','1\ne')
['1', 'e']
re.findall(r'.','1\ne',re.S)
['1', '\n', 'e']