编写代码时, 经常要匹配特定字符串, 或某个模式的字符串, 一般会借助字符串函数, 或正则表达式完成.
对于正则表达式, 有些字符具有特殊含义, 需使用反斜杠字符'\'转义, 使其表示本身含义. 如想匹配字符'\', 却要写成'\\\\', 很是困扰. Python中Raw string解决了该问题, 只需给'\'加上前缀'r'即可, 如r'\n', 表示'\'和'n'两个普通字符, 而不是原来的换行. 前缀'r'类似于sed命令的-r(use extended regular expressions)参数.
正则表达式可包括两部分, 一是正常字符, 表本身含义; 二是特殊字符, 表一类正常字符, 或字符数量...
re模块提供了诸多方法进行正则匹配.
match Match a regular expression pattern to the beginning of a string.
search Search a string for the presence of a pattern.
sub Substitute occurrences of a pattern found in a string.
subn Same as sub, but also return the number of substitutions made.
split Split a string by the occurrences of a pattern.
findall Find all occurrences of a pattern in a string.
finditer Return an iterator yielding a match object for each match.
purge Clear the regular expression cache.
escape Backslash all non-alphanumerics in a string.
还有compile函数, 其较特殊, 将匹配模式编译为一个正则表达式对象(RegexObject, _sre.SRE_Pattern), 并返回, 该对象仍然可以使用上述这些函数. 这也从侧面说明了, 对于re模块, 有非编译和编译两种使用方式, 如下所示.
1.
result = re.match(pattern, string)
2.
prog = re.compile(pattern)
result = prog.match(string)
它们达到的效果是相同的, 只是后者暂存了正则表达式对象, 对于某块代码中频繁使用该正则表达式的情形, 后者性能一般会高于前者.
对于match()和search()匹配成功, 会返回一个匹配对象(Match Object, _sre.SRE_Match), 其也有若干方法, 下面几个较常用.
group
group([group1, ...]) -> str or tuple.
Return subgroup(s) of the match by indices or names.
For 0 returns the entire match.
groups(...)
groups([default=None]) -> tuple.
Return a tuple containing all the subgroups of the match, from 1.
The default argument is used for groups
that did not participate in the match
end(...)
end([group=0]) -> int.
Return index of the end of the substring matched by group.
start(...)
start([group=0]) -> int.
Return index of the start of the substring matched by group.
至此对re模块框架性梳理就这样了, 给出些例子, 对上面的内容总结下.
1.
In [23]: text = "He was carefully disguised but captured quickly by police."
In [24]: re.findall(r"\w+ly", text)
Out[24]: ['carefully', 'quickly']
2.
In [25]: m = re.match(r"(\w+) (\w+)", "Isaac Newton, physicist")
In [26]: m.group(0)
Out[26]: 'Isaac Newton'
In [27]: m.group(1)
Out[27]: 'Isaac'
In [28]: m.group(2)
Out[28]: 'Newton'
In [29]: m.group(1, 2)
Out[29]: ('Isaac', 'Newton')
3.
In [31]: account = "abcxyz_"
In [32]: replace_regex = re.compile(r'_$')
In [33]: replace_regex.sub(account[0], account)
Out[33]: 'abcxyza'
正则表达式使用中的细节还有很多, 这里无法尽数, 实践过程中慢慢体会和总结吧.