Core Syntax Fundamentals: Anchors, Classes, and Quantifiers
- • Regular expressions (Regex) provide a formal language for pattern matching within text. Core building blocks include:
- • Anchors (^ for start of string/line, $ for end of string/line, \b for word boundary).
- • Character Classes (\d for digits [0-9], \w for word characters [A-Za-z0-9_], \s for whitespace).
- • Quantifiers (+ for 1 or more, * for 0 or more, ? for optional 0 or 1, {min,max} for bounded repetitions).
- • Greedy vs Lazy: Standard quantifiers are greedy, matching as much text as possible. Adding ? makes them lazy (matching the minimum text required).
// Greedy vs Lazy Quantifier Comparison
const html = '<div class="card">Hello</div><div class="footer">World</div>';
// ❌ Greedy: Matches from the first '<div' to the final '</div>'
const greedy = html.match(/<div.*<\/div>/);
// ✅ Lazy: Matches only the first individual container
const lazy = html.match(/<div.*?<\/div>/);