re#
Python’s built-in module for regular expressions.
Basic Functions#
re.compile(pattern: str, flags: int = 0) -> re.Pattern: Compiles a regex string into a reusablere.Patternobject.re.search(pattern: str, string: str, flags: int = 0) -> re.Match | None: Scans throughstringfor the first location wherepatternmatches.re.match(pattern: str, string: str, flags: int = 0) -> re.Match | None: Checks for a match only at the beginning ofstring.re.fullmatch(pattern: str, string: str, flags: int = 0) -> re.Match | None: Checks whether the entirestringmatchespattern.re.finditer(pattern: str, string: str, flags: int = 0) -> Iterator[re.Match]: Returns an iterator yieldingre.Matchobjects over all non-overlapping matches.re.findall(pattern: str, string: str, flags: int = 0) -> list[str] | list[tuple[str, ...]]: Returns all non-overlapping matches as a list of strings (0 or 1 capturing group) or tuples (multiple capturing groups).re.sub(pattern: str, repl: str | Callable[[re.Match], str], string: str, count: int = 0, flags: int = 0) -> str: Replaces matches withrepland returns the new string.re.split(pattern: str, string: str, maxsplit: int = 0, flags: int = 0) -> list[str]: Splitsstringby occurrences ofpattern.
Flags#
Passed via the flags parameter in module-level functions and re.compile(). Combine multiple flags with the bitwise OR operator |.
re.IGNORECASE/re.I: Case-insensitive matchingre.MULTILINE/re.M: Makes^and$match the start and end of each linere.DOTALL/re.S: Makes.match any character including newline\nre.VERBOSE/re.X: Ignores whitespace and#comments inside the pattern for multi-line formattingre.ASCII/re.A: Restricts\w,\d, and\sto ASCII-only matching instead of Unicode
eg. re.search(r"^error", text, re.I | re.M)
re.compile#
Module-level functions (re.search, re.findall, etc.) look up an internal cache on every call. Precompiling a re.Pattern object with re.compile() provides three advantages:
- Loop Performance: Eliminates repeated wrapper function calls and cache lookup overhead when scanning millions of lines in a loop.
- Flag Binding: Binds flags like
re.Idirectly into a reusablere.Patternconstant. - Substring Bounds (
pos,endpos): Unlocksposandendposindex parameters not available on module-level functions, avoiding slice allocations.
eg.
import re
LOG_RE = re.compile(r'^(\S+) .* "(GET|POST) (\S+)"', re.I)
for line in lines:
if m := LOG_RE.search(line):
print(m.group(3))re.Pattern Methods#
Module-level functions internally delegate to re.compile(pattern, flags).<method>(...), so behavior is identical. Only two signature rules change:
- Omitted Arguments: Provides the same 7 methods (
search,match,fullmatch,finditer,findall,sub,split) withpatternandflagsomitted since they are already bound to there.Patterninstance. - Slice Bounds (
pos,endpos): The 5 search methods (search,match,fullmatch,finditer,findall) accept(string: str, pos: int = 0, endpos: int = sys.maxsize)to restrict matching to[pos, endpos)(subandsplitdo not takepos/endpos).
eg.
import re
TOKEN_RE = re.compile(r"\d+")
line = "id=42, cost=150, retry=3"
# Search starting at index 7 without allocating line[7:]
m = TOKEN_RE.search(line, pos=7)
if m:
print(m.group(0)) # 150re.Match Methods#
Methods on an m: re.Match object returned when search, match, or finditer succeeds. Capturing groups (...) are numbered starting from 1 in left-to-right order of opening parentheses.
m.group(group: int = 0) -> str: Returns the matched string for the specified group.m.group()/m.group(0): Entire matched stringm.group(1),m.group(2), …: Substring matched by the 1st, 2nd(...)capturing groupm.group(1, 2): Passing multiple group indices returns atuple[str, ...]
m.groups(default: str | None = None) -> tuple[str | None, ...]: Returns all capturing groups from1onward as(m.group(1), m.group(2), ...)(excludes group0).m.start(group: int = 0) -> int/m.end(group: int = 0) -> int: Returns the start and end indices of the specified group.m.span(group: int = 0) -> tuple[int, int]: Returns the(start, end)index tuple of the specified group.
Examples#
Using re.Match Methods#
import re
text = "Contact: 010-1234-5678"
match = re.search(r"(\d{3})-(\d{4})-(\d{4})", text)
if match:
print(match.group(0)) # 010-1234-5678 (entire match)
print(match.group(1)) # 010 (1st group)
print(match.group(2)) # 1234 (2nd group)
print(match.group(1, 2)) # ('010', '1234')
print(match.groups()) # ('010', '1234', '5678')
print(match.span()) # (9, 22)finditer and findall#
import re
text = "apple, orange, banana"
# finditer: returns iterator of Match objects
matches = re.finditer(r"\w+", text)
for m in matches:
print(m.group())
# findall: returns list of strings
fruits = re.findall(r"\w+", text)
print(fruits) # ['apple', 'orange', 'banana']