Cheat Sheet - Linux: /linux/ - CLI: /linux/cli/ - locate vs type vs which vs whereis: /linux/cli/locate-vs-type-vs-which-vs-whereis/ - make: /linux/cli/make/ - awk: /linux/cli/awk/ - find: /linux/cli/find/ - grep: /linux/cli/grep/ - pgrep: /linux/cli/pgrep/ - ps: /linux/cli/ps/ - pstree: /linux/cli/pstree/ - trap: /linux/cli/trap/ - xargs: /linux/cli/xargs/ - Shell: /linux/shell/ - BASH_SOURCE: /linux/shell/bash-source/ - Redirection: /linux/shell/redirection/ - Special Variables: /linux/shell/special-variables/ - Scripting Tips: /linux/shell/script-tips/ - set -o vi: /linux/shell/bash-vi-mode/ - Shell Processing Order: /linux/shell/process-order/ - What are Interactive and Login Shells?: /linux/shell/interactive-login/ - Double Quote Expansion: /linux/shell/shell-expansion/ - System Programming: /linux/system-programming/ - File I/O: /linux/system-programming/file-io/ - Process: /linux/system-programming/process/ - Shared Libraries: /linux/system-programming/shared-libraries/ - Kernel: /linux/kernel/ - Go: /programming/go/ - Concurrency: /programming/go/concurrency/ - CSP (Communicating Sequential Processes) and Channels: /programming/go/concurrency/csp/ - Channel: /programming/go/concurrency/channel/ - Select: /programming/go/concurrency/select/ - sync: /programming/go/concurrency/sync/ - Concurrency Patterns: /programming/go/concurrency/patterns/ - Goroutines and the Go Runtime: /programming/go/concurrency/runtime/ - Standard Library: /programming/go/std/ - os: /programming/go/std/os/ - context: /programming/go/std/context/ - io: /programming/go/std/io/ - json: /programming/go/std/json/ - net/http: /programming/go/std/net-http/ - slog: /programming/go/std/slog/ - testing: /programming/go/std/testing/ - time: /programming/go/std/time/ - Ellipsis (...): /programming/go/ellipsis/ - error: /programming/go/error/ - Function: /programming/go/function/ - Go Tool: /programming/go/tool/ - Interface: /programming/go/interface/ - Map: /programming/go/map/ - Package and Module: /programming/go/package-module/ - Pointer: /programming/go/pointer/ - Slice: /programming/go/slice/ - String: /programming/go/string/ - Switch: /programming/go/switch/ - Comparison: /programming/go/comparison/ - defaultdict: /programming/python/collections/defaultdict/ - heapq: /programming/python/collections/heapq/ - @cache: /programming/python/cache/ - abc: /programming/python/abc/ - bisect: /programming/python/bisect/ - Type Hints: /programming/python/type-hints/ - Passing Mechanism: /programming/python/passing-mechanism/ - uv: /programming/python/uv/ - *args and **kwargs: /programming/python/args-kwargs/ - re: /programming/python/re/ - C: /programming/c/ - Pointers and Arrays: /programming/c/pointer/ - Syntax Basics: /programming/c/syntax-basics/ - static: /programming/c/static/ - Bit Manipulation: /programming/c/bit-manipulation/ - C vs C++: /programming/c/c-vs-cpp/ - stdatomic: /programming/c/stdatomic/ - C++: /programming/cpp/ - RAII (Resource Acquisition Is Initialization): /programming/cpp/raii/ - Copy Elision & Move Semantics: /programming/cpp/copy-elision-and-move-semantics/ - Most Vexing Parse & In-Class Initializer: /programming/cpp/most-vexing-parse/ - C++ Keywords Reference: /programming/cpp/keywords/ - C++ Primer: /programming/cpp/primer/ - Variables and Basic Types: /programming/cpp/primer/variables-and-basic-types/ - Expressions: /programming/cpp/primer/expressions/ - Type Conversions and Casts: /programming/cpp/primer/type-conversions-and-casts/ - Statements: /programming/cpp/primer/statements/ - Functions: /programming/cpp/primer/functions/ - Classes: /programming/cpp/primer/classes/ - The IO Library: /programming/cpp/primer/io-library/ - STL: /programming/cpp/primer/stl/ - Lambda Expressions: /programming/cpp/primer/lambda/ - Smart Pointers: /programming/cpp/primer/smart-pointers/ - Copy Control: /programming/cpp/primer/copy-control/ - Overloaded Operations and Conversions: /programming/cpp/primer/operator-overloading/ - Object-Oriented Programming (OOP): /programming/cpp/primer/oop/ - Templates and Generic Programming: /programming/cpp/primer/templates/ - Namespaces: /programming/cpp/primer/namespaces/ - Pointers to Class Member: /programming/cpp/primer/pointers-to-class-member/ - Advanced: /programming/cpp/advanced/ - Error Handling: /programming/cpp/advanced/error-handling/ - Concurrency & Threading: /programming/cpp/advanced/concurrency/ - Unit Testing: /programming/cpp/advanced/unit-testing/ - Comparison: /programming/comparison/ - Kubernetes: /cloud-devops/kubernetes/ - Fleet: /cloud-devops/kubernetes/gke/fleet/ - Kustomize vs Helm: /cloud-devops/kubernetes/kustomize-vs-helm/ - API Extension: /cloud-devops/kubernetes/api-extension/ - Concept: /cloud-devops/kubernetes/kueue/concept/ - DRA: /cloud-devops/kubernetes/dra/ - Secret Manager: /cloud-devops/terraform/google-secret-manager/ - Knowledge: /network/knowledge/ - PDU: /network/knowledge/osi-model/ - curl: /network/cli/curl/ - Concurrency Concepts: /cs/concurrency-and-parallelism/concepts/ - Concurrency vs Parallelism: /cs/concurrency-and-parallelism/concurrency-vs-parallelism/ - Mutex vs Atomic: /cs/concurrency-and-parallelism/mutex-vs-atomic/ - Regular Expression: /cs/regular-expression/ - Multiplexer vs Dispatcher: /cs/multiplexer-vs-dispatcher/ - Driver and Runtime: /ai-ml/gpu/driver-and-runtime/ - Serving: /ai-ml/serving/ - Dotfiles: /dotfiles/ - Git: /dotfiles/git/ - Cheat Sheet: /dotfiles/git/cheat-sheet/ - revisions: /dotfiles/git/revisions/ - Submodule vs Worktree: /dotfiles/git/submodule-vs-worktree/ - checkout, reset -> switch, restore: /dotfiles/git/checkout-switch-restore-reset/ - rebase: /dotfiles/git/rebase/ - Branching and Merging: /dotfiles/git/branching-merging/ - Vim: /dotfiles/vim/ - Plugin: /dotfiles/vim/plugin/ - auto-pairs: /dotfiles/vim/plugin/auto-pairs/ - vim-commentary: /dotfiles/vim/plugin/vim-commentary/ - vim-easymotion: /dotfiles/vim/plugin/vim-easymotion/ - vim-surround: /dotfiles/vim/plugin/vim-surround/ - Marks: /dotfiles/vim/tips/marks/ - vimrc: /dotfiles/vim/vimrc/ - lf: /dotfiles/lf/ # `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 reusable `re.Pattern` object. - `re.search(pattern: str, string: str, flags: int = 0) -> re.Match | None`: Scans through `string` for the first location where `pattern` matches. - `re.match(pattern: str, string: str, flags: int = 0) -> re.Match | None`: Checks for a match only at the beginning of `string`. - `re.fullmatch(pattern: str, string: str, flags: int = 0) -> re.Match | None`: Checks whether the entire `string` matches `pattern`. - `re.finditer(pattern: str, string: str, flags: int = 0) -> Iterator[re.Match]`: Returns an iterator yielding `re.Match` objects 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 with `repl` and returns the new string. - `re.split(pattern: str, string: str, maxsplit: int = 0, flags: int = 0) -> list[str]`: Splits `string` by occurrences of `pattern`. ## 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 matching - `re.MULTILINE` / `re.M`: Makes `^` and `$` match the start and end of each line - `re.DOTALL` / `re.S`: Makes `.` match any character including newline `\n` - `re.VERBOSE` / `re.X`: Ignores whitespace and `#` comments inside the pattern for multi-line formatting - `re.ASCII` / `re.A`: Restricts `\w`, `\d`, and `\s` to 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.I` directly into a reusable `re.Pattern` constant. - **Substring Bounds (`pos`, `endpos`)**: Unlocks `pos` and `endpos` index parameters not available on module-level functions, avoiding slice allocations. eg. ```python 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).(...)`, so behavior is identical. Only two signature rules change: - **Omitted Arguments**: Provides the same 7 methods (`search`, `match`, `fullmatch`, `finditer`, `findall`, `sub`, `split`) with `pattern` and `flags` omitted since they are already bound to the `re.Pattern` instance. - **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)` (`sub` and `split` do not take `pos`/`endpos`). eg. ```python 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)) # 150 ``` ## `re.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 string - `m.group(1)`, `m.group(2)`, ...: Substring matched by the 1st, 2nd `(...)` capturing group - `m.group(1, 2)`: Passing multiple group indices returns a `tuple[str, ...]` - `m.groups(default: str | None = None) -> tuple[str | None, ...]`: Returns all capturing groups from `1` onward as `(m.group(1), m.group(2), ...)` (excludes group `0`). - `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 ```python 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` ```python 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'] ``` --- See [General Regular Expression Concepts]({{< relref "/cs/regular-expression.md" >}})