预编译模式

import re

precompiled_pattern = re.compile(r"(\d+)")
matches = precompiled_pattern.search("The answer is 41!")
matches.group(1)
# Out: 41

matches = precompiled_pattern.search("Or was it 42?")
matches.group(1)
# Out: 42

编译模式允许稍后在程序中重用它。但是,请注意 Python 缓存最近使用的表达式( docsSO 答案 ),因此 一次只使用几个正则表达式的程序不必担心编译正则表达式

import re

precompiled_pattern = re.compile(r"(.*\d+)")
matches = precompiled_pattern.match("The answer is 41!")
print(matches.group(1))
# Out: The answer is 41

matches = precompiled_pattern.match("Or was it 42?")
print(matches.group(1))
# Out: Or was it 42

它可以与 re.match() 一起使用。