GROUPS & ALTERNATION
Backreferences
A backreference like `\1` matches the exact text a group already captured.
Every plain group stores the text it actually matched, numbered by opening paren: first group is \1, second \2, and so on. A backreference means "the exact same text again" - not the same pattern, the same text. So (\w+)\1 matches "byebye" but not "byelo": the pattern \w+ would happily match "lo", but \1 demands a literal repeat of whatever the group grabbed, here "bye".
Classic use: finding doubled words. \b(\w+) \1\b matches "is is" and "the the". The boundaries matter - without them, the second "is" in "this is" could pair with the "is" hiding inside "this".
A real-world favorite is matching a quoted string whose closing quote matches its opening quote. (["\']).*?\1 captures the opening quote - single or double - then .*? takes the shortest run up to a \1, which forces the same quote character to close it. So in say "hi" or \'bye\' it pairs the double quotes into one match and the single quotes into another, and it never lets a " close a string that opened with a \'.
Counting parens gets error-prone fast. You can also NAME a group: (?<word>\w+) \k<word> reads better and survives reordering, and in a replacement the name is $<word>. MDN: named capturing group.
Match every doubled word - a word, a space, then the same word again.
this is is a typo
the the end
nothing wrong here
Match any character immediately followed by itself - the doubled letters in a word.
balloon
hello
abc
Match each quoted string. The closing quote must match the opening quote - a string opened with " ends with ", one opened with ' ends with '.
say "hi" or 'bye'
name = 'Sam'
no quotes here