Regular expressions (Regex) provide developers with a compact algebraic notation for matching complex textual patterns across strings, files, logs, and user inputs.
1. Regex Grammar Foundations
At their core, regex patterns evaluate characters either literally (e.g. abc) or via metacharacters that represent classes of characters:
\d: Any digit (0-9).\w: Any word character (letters, numbers, underscore).\s: Any whitespace (spaces, tabs, newlines).[a-z0-9]: Custom character sets.
2. Greedy vs Lazy Quantifiers
By default, quantifiers like * (0 or more) and + (1 or more) are greedy — they match as much text as possible. Appending a question mark (*? or +?) makes them lazy, matching the smallest possible substring.
3. Lookahead & Lookbehind Assertions
Zero-width assertions match characters without consuming them:
(?=...)Positive Lookahead: Matches if pattern follows.(?!...)Negative Lookahead: Matches if pattern does not follow.(?<=...)Positive Lookbehind: Matches if pattern precedes.(?<!...)Negative Lookbehind: Matches if pattern does not precede.
4. Preventing Catastrophic Backtracking
When a regex engine with backtracking encounters ambiguous nested quantifiers (e.g. ([a-zA-Z]+)+$) evaluated against non-matching text, execution time can grow exponentially (O(2^n)), freezing the server thread or browser tab in a Regular Expression Denial of Service (ReDoS).