正则表达式
通过事先规定好一些特殊字符的匹配规则,然后利用这些字符进行组合来匹配各种复杂的字符串场景。
Python的re模块
re 模块使 Python 语言拥有全部的正则表达式功能。
compile 函数根据一个模式字符串和可选的标志参数生成一个正则表达式对象。该对象拥有一系列方法用于正则表达式匹配和替换。
基本语法
re.match函数
r
e
.
m
a
t
c
h
(
p
a
t
t
e
r
n
,
s
t
r
i
n
g
,
f
l
a
g
s
=
0
)
re.match(pattern, string, flags=0)
re.match(pattern,string,flags=0)
re.match 尝试从字符串的起始位置匹配一个模式,如果不是起始位置匹配成功的话,match() 就返回 none。
用 group(num) 或 groups() 匹配对象函数来获取匹配表达式。
re.search方法
r
e
.
s
e
a
r
c
h
(
p
a
t
t
e
r
n
,
s
t
r
i
n
g
,
f
l
a
g
s
=
0
)
re.search(pattern, string, flags=0)
re.search(pattern,string,flags=0)
re.search 扫描整个字符串并返回第一个成功的匹配。
re.match只匹配字符串的开始,如果字符串开始不符合正则表达式,则匹配失败,函数返回None;而re.search匹配整个字符串,直到找到一个匹配。
检索和替换
Python 的 re 模块提供了re.sub用于替换字符串中的匹配项
r
e
.
s
u
b
(
p
a
t
t
e
r
n
,
r
e
p
l
,
s
t
r
i
n
g
,
c
o
u
n
t
=
0
,
f
l
a
g
s
=
0
)
re.sub(pattern, repl, string, count=0, flags=0)
re.sub(pattern,repl,string,count=0,flags=0)
re.compile 函数
compile 函数用于编译正则表达式,生成一个正则表达式( Pattern )对象,供 match() 和 search() 这两个函数使用。
r
e
.
c
o
m
p
i
l
e
(
p
a
t
t
e
r
n
[
,
f
l
a
g
s
]
)
re.compile(pattern[, flags])
re.compile(pattern[,flags])