Python正则表达式(一)

match(pattern,string,flag=0)    匹配成功就返回匹配对象,匹配失败就返回None。

search(pattern,string,flag=0)   在字符串中搜索第一次出现的正则表达式模式,如果匹配成功,就返回匹配对象,匹配失败就返回None。

 

匹配对象需要调用group() 或 groups() 方法。

group()要么返回整个匹配对象,要么返回特定的子组。

groups()返回一个包含唯一或者全部子组的元组。如果没走子组要求,将返回空元组。

 

findall(pattern,string[,flags])  查找字符串中所有出现的正则表达式模式,并返回一个匹配列表。

finditer(pattern,string[,flags])  与findall()函数相同,但返回的不是一个列表,而是一个迭代器。对于每一次匹配,迭代器都返回一个匹配对象。

import re

s = 'this and that'
m = re.findall(r'(th\w+) and (th\w+)',s,re.I)
print 1,m

m = re.finditer(r'(th\w+) and (th\w+)',s,re.I)
print 2,m

for g in re.finditer(r'(th\w+) and (th\w+)',s,re.I):
print 3,g.group()
print 4,g.group(1)
print 5,g.group(2)
print 6,g.groups()

m = re.findall(r'(th\w+)',s,re.I)
print 7,m

g = re.finditer(r'(th\w+)',s,re.I)
m = g.next()
print 8,m.groups()
print 9,m.group(1)
m = g.next()
print 10,m.groups()
print 11,m.group(1)

print 12,[g.group() for g in re.finditer(r'(th\w+)',s,re.I)]

运行结果:

1 [('this', 'that')]
2 <callable-iterator object at 0x02766FD0>
3 this and that
4 this
5 that
6 ('this', 'that')
7 ['this', 'that']
8 ('this',)
9 this
10 ('that',)
11 that
12 ['this', 'that']

 

posted @ 2017-07-11 22:06  孙连城  阅读(265)  评论(0编辑  收藏  举报