Lessons · Regex · \1 in the replacement
Putting the pieces back in a different order
In the replacement, \1 and \2 stand for what those groups captured. The replacement is not a pattern; it is text with holes in it.
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
Reformatting dates, swapping a name round, rewriting a URL: the parts you want are already in the groups.
How to think about it
Write the pattern so the pieces you need are captured, then describe the output with the numbers in the order you want them.
Worked example
re.sub(r'(\w+) (\w+)', r'\2 \1', 'hello world')The two groups, swapped.
re.sub(r'(\d{4})-(\d{2})', r'\2/\1', '2026-09')Year and month, reordered.re.sub(r'(\d)', r'\g<1>0', 'a1b2')\g<1> when a digit follows, or \10 would read as group ten.
Your turn
Swap the two words round.
re.sub(r'(\w+) (\w+)', r' \1', 'hello world')
Test a pattern against real text
The trap
Write the replacement as a raw string. In an ordinary string '\1' is the character with code 1, and re never sees the backslash.
Practise \1 in the replacement on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.