1.3.5 限制搜索
有些情况下,可以提前知道只需要搜索整个输入的一个子集,在这些情况下,可以告诉re限制搜索范围从而进一步约束正则表达式匹配。例如,如果模式必须出现在输入开头,那么使用match()而不是search()会锚定搜索,而不必显示地在搜索模式中包含一个锚。
import re
text = 'This is some text -- with punctuation.'
pattern = 'is'
print('Text :',text)
print('Pattern:',pattern)
m = re.match(pattern,text)
print('Match :',m)
s = re.search(pattern,text)
print('Search:',s)
由于字面量文本is未出现在输入文本的开头,因此使用match()时找不到它。不过,这个序列在文本中另外还出现了两次,所以search()能找到。
运行结果:
Text : This is some text – with punctuation.
Pattern: is
Match : None
Search: <re.Match object; span=(2, 4), match=‘is’>
fullmatch()方法要求整个输入字符串与模式匹配。
import re
text = 'This is some text -- with punctuation.'
pattern = 'is'
print('Text :',text)
print('Pattern :',pattern)
m = re.search(pattern,text)
print('Search :',m)
s = re.fullmatch(pattern,text)
print('Full match:',s)
这里search()显示模式确实出现在输入中,但是它没能消费所有输入,所以fullmatch()不会报告匹配。
运行结果:
Text : This is some text – with punctuation.
Pattern : is
Search : <re.Match object; span=(2, 4), match=‘is’>
Full match: None
已编译正则表达式的search()方法还接受可选的start和end位置参数,将搜索范围限制到输入的一个子串中。
import re
text = 'This is some text -- with punctuation.'
pattern = re.compile(r'\b\w*is\w*\b')
print('Text:',text)
print()
pos = 0
while True:
match = pattern.search(text,pos)
if not match:
break
s = match.start()
e = match.end()
print(' {:>2d} : {:>2d} = "{}"'.format(s,e - 1,text[s:e]))
# Move forward in text for the next search.
pos = e
运行结果:
Text: This is some text – with punctuation.
0 : 3 = “This”
5 : 6 = “is”