On this page
re.escape
Prev: re.error | Up: re | Next: re.findall
Rel: re.compile, re.error, re.findall, re.finditer
Ref: docs.python.org — re.escape
Tags: #public #python3 #stdlib #re
Import
import re
from re import escape
Signature & Overview
re.escape(pattern)
Escape special characters in a string.
Usage
import re
literal = "price is $9.99 (USD)"
pat = re.compile(re.escape(literal))
assert pat.search("Total: price is $9.99 (USD) today") is not None
Gotchas
- Always escape untrusted or dynamic literal substrings: Otherwise characters like
.,*,+,?,(,[act as regex metacharacters. - For
re.sub()replacements,re.escape()is not enough: Replacement strings interpret\1/\g<1>—use alambda m: replacementwhen inserting arbitrary literal text.
REPL Inspect
from re import escape
help(escape)
Linked from
- tuts/python3/stdlib_module/re
- tuts/python3/stdlib_module/re/compile
- tuts/python3/stdlib_module/re/error
- tuts/python3/stdlib_module/re/findall
- tuts/python3/stdlib_module/re/finditer
- tuts/python3/stdlib_module/re/fullmatch
- tuts/python3/stdlib_module/re/match
- tuts/python3/stdlib_module/re/Match_class
- tuts/python3/stdlib_module/re/Pattern
- tuts/python3/stdlib_module/re/PatternError
- tuts/python3/stdlib_module/re/purge
- tuts/python3/stdlib_module/re/RegexFlag
- tuts/python3/stdlib_module/re/search
- tuts/python3/stdlib_module/re/split
- tuts/python3/stdlib_module/re/sub
- tuts/python3/stdlib_module/re/subn
Related notes
- tuts/python3/stdlib_module/re/compile Linked here; links to this page; shared tags: #re, #stdlib
- tuts/python3/stdlib_module/re/error Linked here; links to this page; shared tags: #re, #stdlib
- tuts/python3/stdlib_module/re/findall Linked here; links to this page; shared tags: #re, #stdlib
- tuts/python3/stdlib_module/re/finditer Linked here; links to this page; shared tags: #re, #stdlib
- tuts/python3/stdlib_module/re Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/re/fullmatch links to this page; shared tags: #re, #stdlib
- tuts/python3/stdlib_module/re/match links to this page; shared tags: #re, #stdlib
- tuts/python3/stdlib_module/re/Match_class links to this page; shared tags: #re, #stdlib
- tuts/python3/stdlib_module/re/Pattern links to this page; shared tags: #re, #stdlib
- tuts/python3/stdlib_module/re/PatternError links to this page; shared tags: #re, #stdlib