本文实例总结了Python正则表达式常用函数。分享给大家供大家参考,具体如下:
re.match()
函数原型:
match(pattern, string, flags=0)
Try to apply the pattern at the start of the string,
returning a match object, or None if no match was found.
函数作用:
re.match函数尝试从字符串的开头开始匹配一个模式,如果匹配成功,返回一个匹配成功的对象,否则返回None。
参数说明:
pattern:匹配的正则表达式
string:要匹配的字符串
flags:标志位,用于控制正则表达式的匹配方式。如是否区分大小写、是否多行匹配等。
我们可以使用group()或groups()匹配对象函数来获取匹配后的结果。
group()
group(...)
group([group1, ...]) -> str or tuple.
Return subgroup(s) of the match by indices or names.
For 0 returns the entire match.
获得一个或多个分组截获的字符串;指定多个参数时将以元组形式返回。group1可以使用编号也可以使用别名;编号0代表匹配的整个子串;默认返回group(0);没有截获字符串的组返回None;截获了多次的组返回最后一次截获的子串。
groups()
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
以元组形式返回全部分组截获的字符串。相当于调用group(1,2,…last)。没有截获字符串的组以默认值None代替。
实例
import reline = "This is the last one"res = re.match( r'(.*) is (.*?) .*', line, re.M|re.I)if res: print "res.group() : ", res.group() print "res.group(1) : ", res.group(1) print "res.group(2) : ", res.group(2) print "res.groups() : ", res.groups()else: print "No match!!"
re.M|re.I:这两参数表示多行匹配|不区分大小写,同时生效。
细节实例:
>>> re.match(r'.*','.*g3jl/nok').group()'.*g3jl'
.(点)表示除换行符以外的任意一个字符,*(星号)表示匹配前面一个字符0次1次或多次,这两联合起来使用表示匹配除换行符意外的任意多个字符,所以出现以上的结果。
1、re.match(r'.*..', '..').group()'..'2、>>> re.match(r'.*g.','.*g3jlok').group()'.*g3'3、>>> re.match(r'.*...', '..').group()Traceback (most recent call last): File "<stdin>", line 1, in <module>AttributeError: 'NoneType' object has no attribute 'group'
上面两例子为什么有结果呢?这是因为第一个例子.*..中的.*匹配了0次,后面的..匹配字符串中..,而第二个例子中的 .* 匹配了一次,匹配字符串中的 .*,g匹配了后面的g字符,最后一个.号匹配了。
新闻热点
疑难解答