Python Language Regular Expressions (Regex) Precompiled patterns


import re

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

matches ="Or was it 42?")
# Out: 42

Compiling a pattern allows it to be reused later on in a program. However, note that Python caches recently-used expressions (docs, SO answer), so "programs that use only a few regular expressions at a time needn’t worry about compiling regular expressions".

import re

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

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

It can be used with re.match().