本文已参与「新人创作礼」活动, 一起开启掘金创作之路。
re方法属性
.compile()
regex
将正则表达式模式编译成正则表达式对象pattern
正则表达式flags=0
调整表达式的行为, 可以使用 or (|) 组合使用
.A
flags=
让\w
,\W
,\b
,\B
,\d
,\D
,\s
and\S
执行纯 ASCII 匹配,而不是全部Unicode匹配(仅在Unicode模式下有意义, 并在byte模式下被忽略).ASCII
.DEBUG
flags=
显示关于编译表达式的调试信息.I
flags=
执行不区分大小写的匹配.IGNORECASE
.L
flags=
不建议使用???.LOCALE
.M
flags=
使 ^ 匹配的是紧跟换行符之前的位置).MULTILINE
.S
flags=
让 . 也可以匹配到换行符 (默认 . 智能匹配除换行符之外的字符).DOTALL
.X
flags=
更友好的编辑模式, 会忽略正则表达式中的空白符以及未转义的#号及其同一行后面的内容, 这样就可以多行编辑正则表达式, 更有利于阅读.VERBOSE
.search()
MatchNone
返回第一次匹配到的结果, 无匹配则返回 Nonepattern
正则表达式string
要匹配的字符串flags=0
调用表达式的行为
.match()
.search()
只能从字符串的开头位置匹配.fullmatch()
.search()
正则表达式匹配整个字符串 3.4.split()
list
使用正则表达式分割字符串, 返回分割后的字符串列表(若含有捕获组则结果中也会包括捕获内容)pattern
正则表达式string
要匹配的字符串maxsplit=0
最大分割次数flags=0
调用表达式的行为
.findall()
list
.search() 以列表返回所有匹配结果.finditer()
iter
.search() 返回一个包含所有匹配结果的迭代器.sub()
str
将匹配到的字符串替换为replpattern
正则表达式repl
str, fun(match): return strstring
要匹配的字符串count=0
允许替换的最大次数flags=0
调用表达式的行为
.subn()
tuple
.sub() 返回 (替换后的字符串, 替换次数).escape()
str
string 转义除ASCII字母, 数字和 '' 之外的所有字符 ('' 3.3 之后才不再转义).purge()
.error()
已编译的正则表达式对象的方法和属性
.search()
Match
string[, pos[, endpos]].match()
Match
string[, pos[, endpos]].fullmatch()
Match
string[, pos[, endpos]].split()
list
string, maxsplit=0.findall()
list
string[, pos[, endpos]].finditer()
iter
string[, pos[, endpos]].sub()
str
repl, string, count=0.subn()
tuple
repl, string, count=0.flags
flags
正则表达式匹配标志.groups
int
模式中的捕获组数量.groupindex
dict
将 (?P<id>) 定义的任何符号组名称映射到组编号的字典.pattern
str
编译RE对象的模式字符串
Match对象的方法
.expand()
.group()
str
0
默认, 返回匹配结果str
1
返回第一个捕获组捕获的内容Tuple
1, 2
返回两个捕获组内容组成的Tuple
.groups()
Tuple
以元组的方式返回全部捕获组的内容default=None
若捕获组内容为空, 则使用此值填充
.groupdict()
dict
default=None 设有name的捕获组, 返回成一个字典.start()
int
[group] 匹配开始的位置.end()
int
[group] 匹配结束的位置.span()
Tuple
[group] (匹配开始的位置, 匹配结束的未至).pos
int
传递的pos值.endpos
int
传递的endpos值.lastindex
int
最后匹配的(最后一个右括号对应的)捕获组的整数索引.lastgroup
str/None
最后匹配的捕获组的名称, 如果没有名称或没有捕获组返回None.re
regrex
编译后的正则表达式对象.string
str
要匹配的字符串