( )

在正则表达式中,匹配字符时候,若有用括号分组的情况,则findall函数会优先返回分组中匹配的内容,如一下代码显示:

#!/usr/bin/python
#coding:utf8

import re

res = r"(hello) world"
res1 = r"(hello|hi) world"
res2 = r"hello world"
s = "hello world hi world"

print re.findall(res, s) #显示hello
print "#"*20
print re.findall(res1, s) #显示hello或者hi
print "#"*20
print re.findall(res2, s) #显示 hello world
$ python e8.py 
['hello']
####################
['hello', 'hi']
####################
['hello world']
Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐