Hone

Lessons · Regex · backreferences

The same thing again

\1 matches whatever group 1 captured, so (\w)\1 is a doubled letter.

Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.

What it is for

Repeated words, matching open and close quotes, duplicated fields.

How to think about it

Must this be the SAME thing as before? Capture the first occurrence, then refer back with \N where the repeat should be.

Worked example

pattern: (['"]).*?\1
Whatever quote opened must close.
text: say 'hi' now
Matches 'hi'.
text: say 'hi" now
No match: mismatched quotes.

Your turn

Two identical digits in a row.

(\d)

The trap

In a replacement string the syntax is $1, not \1, in JavaScript.

Practise backreferences on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.