On this page
re.compile
Up: re | Next: re.error
Rel: re.error, re.escape, re.findall, re.finditer
Ref: docs.python.org — re.compile
Tags: #public #python3 #stdlib #re
Import
import re
from re import compile
Signature & Overview
re.compile(pattern, flags=0)
Compile a regular expression pattern, returning a Pattern object.
Usage
import re
word_re = re.compile(r"\b[a-z]+\b", re.IGNORECASE)
assert word_re.findall("Hello, 123 world!") == ["Hello", "world"]
Gotchas
- Always use raw strings (
r"..."): Withoutr,\bbecomes a backspace character instead of a word boundary. - Module-level
refunctions already cache recent patterns: Compile explicitly when reusing a pattern in tight loops, passing it around, or needingpos/endposbounds.
REPL Inspect
from re import compile
help(compile)
Linked from
- tuts/python3/stdlib_module/re
- tuts/python3/stdlib_module/re/error
- tuts/python3/stdlib_module/re/escape
- 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/error Linked here; links to this page; shared tags: #re, #stdlib
- tuts/python3/stdlib_module/re/escape 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