CKTIS / Python
re.escape
Quotes regular-expression metacharacters so that input is matched literally inside a pattern.
Version: Python 3.14; repository image, production runtime not attested
Syntax
re.escape(pattern)Quotes regular-expression metacharacters so that input is matched literally inside a pattern.
Escaping is for pattern construction. Substitution replacement strings use separate escape rules.
Use escape on literal input before embedding it in a regex pattern. It quotes regex-significant characters and returns the same data kind (text or bytes). In the example the plus becomes a literal plus, so a+b matches and aaab fails. Replacement templates passed to sub use different rules; a callable can return literal replacement text.
import re
text = "a+b.c"
assert re.fullmatch(re.escape(text), text)
assert re.fullmatch(re.escape(text), "aabxc") is None
assert re.fullmatch(re.escape(b"[x]"), b"[x]")
Examples
import re
needle = "a+b"
pattern = re.escape(needle)
print(bool(re.fullmatch(pattern, "a+b")))
print(bool(re.fullmatch(pattern, "aaab")))
Result
True False
Use escape on literal input before embedding it in a regex pattern. It quotes regex-significant characters and returns the same data kind (text or bytes). In the example the plus becomes a literal plus, so a+b matches and aaab fails. Replacement templates passed to sub use different rules; a callable can return literal replacement text.