Text

Regex Tutorial for Developers: Pattern Matching, Lookarounds, and Performance

A comprehensive developer tutorial on regular expressions: character classes, greedy vs lazy quantifiers, lookahead/lookbehind assertions, and preventing ReDoS.

WebUtil Team

1. Regular Expressions Demystified: Character Classes and Wildcards

Regular expressions (regex) are formal sequences of characters defining search patterns for string matching, search-and-replace, and data validation across every major programming language.

  • . matches any single character except newlines.
  • \d matches any digit (0-9); \D matches any non-digit.
  • \w matches any alphanumeric word character plus underscore; \W matches non-word characters.
  • \s matches whitespace (spaces, tabs, newlines); \S matches non-whitespace.
  • [abc] matches any character in the bracket set; [^abc] negates the set.

2. Quantifiers: Greedy vs Lazy Matches

  • Greedy (default): * (0 or more), + (1 or more), ? (0 or 1). Matches as many characters as possible.
  • Lazy (reluctant): Appending ? (*?, +?) forces the engine to match as few characters as possible.

              const html = '<div>First</div><div>Second</div>';
html.match(/<div>.*<\/div>/);  // Greedy: matches '<div>First</div><div>Second</div>'
html.match(/<div>.*?<\/div>/); // Lazy: matches '<div>First</div>'
            

3. Anchors and Boundaries: Start, End, and Word Boundaries

  • ^: Asserts start of string (or start of line in multiline mode /m).
  • $: Asserts end of string (or end of line).
  • \b: Asserts a word boundary position between a word character and non-word character (e.g. \bcat\b matches 'cat' but not 'catch' or 'scat').
Sponsored
Advertisement

4. Advanced Grouping, Named Groups, and Lookarounds

  • Capturing groups (abc) vs Non-capturing groups (?:abc).
  • Named Capturing Groups: (?<year>\d{4})-(?<month>\d{2})
  • Positive Lookahead (?=...): Matches if followed by pattern.
  • Negative Lookahead (?!...): Matches if NOT followed by pattern.
  • Positive Lookbehind (?<=...) and Negative Lookbehind (?<!...).

5. Catastrophic Backtracking (ReDoS) Prevention

Regular Expression Denial of Service (ReDoS) occurs when nested quantifiers (like (a+)+$) cause the NFA regex engine to evaluate exponential permutations on non-matching strings, causing CPU utilization to spike to 100%. Always avoid overlapping nested quantifiers in production authentication patterns.

6. Interactive Real-Time Regex Testing on WebUtil

WebUtil's Regex Tester provides instant interactive regex evaluation with syntax highlighting, capture group inspection, and explanation running 100% locally in your browser.