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‘]
Python正則表達式(一)