Python之re操作

python学习网 2017-06-15 00:00:05

1.re.search():search返回的是查找结果的对象,可以使用group()或groups()方法得到匹配成功的字符串。

  ①group()默认返回匹配成功的整个字符串(忽略pattern中的括号),也可以指定返回匹配成功的括号中第几个字符串(从1开始计数);

  ②groups()以元组的形式返回匹配成功的pattern中括号中的内容,若pattern中没有括号,则返回空元组。

 1 >>> string = 'python'
 2 >>> import re
 3 >>> result = re.search(r'(yt)h(o)', string)
 4 >>> result
 5 <_sre.SRE_Match object at 0x000000000293DE88>
 6 >>> result.group()
 7 'ytho'
 8 >>> result.group(0)  # 参数0无效
 9 'ytho'
10 >>> result.group(1)  # 从1开始计数
11 'yt'
12 >>> result.group(2)
13 'o'
14 >>> result.groups()
15 ('yt', 'o')
16 >>> result.groups(0)  # 传入参数无效
17 ('yt', 'o')
18 >>> result.groups(1)
19 ('yt', 'o')
20 >>> 

 

阅读(890) 评论(0)