1、查找文本中的模式
search()函数取模式和要扫描的文本作为输入,找到这个模式时就返回一个match对象。如果没有找到模式,search()就返回None。
每个match对象包含有关匹配性质的信息,包含原输入字符串,所使用的正则表达式以及模式在原字符串出现的位置。
import re
pattern = 'this'
text = 'Does this text match the pattern?'
match = re.search(pattern, text)
s = match.start()
e = match.end()
print('Found "{}"\nin "{}"\nfrom {} to ("{}")'.format(match.re.pattern, match.string, s, e, text[s:e]))
_____________________输出___________________________________________
Found "this"
in "Does this text match the pattern?"
from 5 to ("9")
start()和end()方法可以提供字符串中的相应索引,指示与模式匹配的文本在字符串中出现的位置。
2、编译表达式
尽管re包括模块级函数,可以处理作为文本字符串的正则表达式,但是对于程序频繁使用的表达式而言,编译它们会更为高效。compile()函数会把一个表达式字符串转换为一个Regex0bject。
import re
regexes = [
re.compile(p)
for p in ['this', 'that']
]
text = 'Does this text match the pattern?'
print('Text: {!r}\n'.format(text))
for regex in regexes:
print('Seeking "{}" ->'.format(regex.pattern),end=' ')
if regex.search(text):
print('match')
else:
print('no match')
_________________________输出_________________________________
Text: 'Does this text match the pattern?'
Seeking "this" -> match
Seeking "that" -> no match
模块级函数会维护一个包含已编译表达式的缓存,不过这个缓存的大小是有限的,另外直接使用已编译表达式可以避免与缓存查找相关的开销。使用已编译表达式的另一个好处为,通过在加载模块时预编译所有的表达式,可以把编译工作转移到应用开始时,而不是当程序响应一个用户动作时才编译。
3、多重匹配
使用search()来查找字面量文本字符串的单个实例,findall()函数会返回输入中与模式匹配而且不重叠的所有子串。
import re
text = 'abbaaabbbbaaaaaa'
pattern = 'ab'
for match in re.findall(pattern, text):
print('Found {!r}'.format(match))
_______________________输出_____________________
Found 'ab'
Found 'ab'
finditer()返回一个迭代器,它会生成Match实例,而不是像findall()那样返回字符串。
import re
text = 'abbaaabbbbaaaaaa'
pattern = 'ab'
for match in re.finditer(pattern, text):
s = match.start()
e = match.end()
print('Found {!r} at {:d}:{:d}'.format(text[s:e],s,e))
_______________________输出_______________________________
Found 'ab' at 0:2
Found 'ab' at 5:7
4、模式语法
正则表达式还支持更加强大的模式。模式可以重复,可以锚定到输入中不同的逻辑位置,可以用紧凑的形式表述而不需要在模式中提取每一个重复的字符
import re
def test_pattern(text,pat