How Regex Matching Works
The regex engine scans your text from left to right, trying to match the pattern at each position. When a match is found, it records the matched text, its position (start and end index), and any captured groups. With the global (g) flag, the engine continues searching from where the last match ended. Without it, only the first match is returned.
Capture Groups and Backreferences
Capture groups () do two things: they group parts of a pattern for quantifiers, and they remember what they matched. Backreferences like \1 match the same text that group 1 captured. This lets you find repeated words: \b(\w+)\s+\1\b matches "the the" but not "the they".
Using Match Results in Code
In JavaScript, str.match(regex) returns an array of matches (with g flag) or a single match object (without g). regex.exec(str) returns detailed match objects with index and groups. str.matchAll(regex) returns an iterator of all match objects — the most modern and flexible approach.