Python常用模块用法分析(3)
m.start() 返回起始位置,m.end()返回结束位置(不包含该位置的字符).
m.span() 返回一个tuple表示(m.start(), m.end())
m.pos(), m.endpos(), m.re(), m.string()
m.re().search(m.string(), m.pos(), m.endpos()) 会得到m本身
m.finditer()可以返回一个iterator,用来遍历所有找到的MatchObject.
for m in re.compile("[ab]").finditer("tatbxaxb"):
print m.span()
高级regexp
| 表示联合多个regexp. A B两个regexp,A|B表示和A匹配或者跟B匹配.
^ 表示只匹配一行的开始行首,^只有在开头才有此特殊意义。
$ 表示只匹配一行的结尾
\A 表示只匹配第一行字符串的开头 ^匹配每一行的行首
\Z 表示只匹配行一行字符串的结尾 $匹配第一行的行尾
\b 只匹配词的边界 例:\binfo\b 只会匹配"info" 不会匹配information
\B 表示匹配非单词边界
示例如下:
>>> print re.compile(r"\binfo\b").match("info ") #使用raw格式 \b表示单词边界 <_sre.SRE_Match object at 0x817aa98> >>> print re.compile("\binfo\b").match("info ") #没有使用raw \b表示退格符号 None >>> print re.compile("\binfo\b").match("\binfo\b ") <_sre.SRE_Match object at 0x8174948>
分组(Group) 示例:
re.compile("(a(b)c)d").match("abcd").groups() ('abc', 'b') #!/usr/local/bin/python import re x = """ name: Charles Address: BUPT name: Ann Address: BUPT """ #p = re.compile(r"^name:(.*)\n^Address:(.*)\n", re.M) p = re.compile(r"^name:(?P<name>.*)\n^Address:(?P<address>.*)\n", re.M) for m in p.finditer(x): print m.span() print "here is your friends list" print "%s, %s"%m.groups()
Compile Flag
用re.compile得到RegxObject时,可以有一些flag用来调整RegxObject的详细特征.
DOTALL, S 让.匹配任意字符,包括换行符\n
IGNORECASE, I 忽略大小写
LOCALES, L 让\w \W \b \B和当前的locale一致
MULTILINE, M 多行模式,只影响^和$(参见上例)
VERBOSE, X verbose模式
- 上一篇:Python切片用法实例教程
- 下一篇:python实现斐波那契递归函数的方法