Backreference cho phép tái sử dụng phần chuỗi đã khớp bởi capturing group trước đó trong cùng pattern.
\1,\2... — tham chiếu group 1, 2... trong pattern.$1,$2... — trong chuỗi replacement củare.sub().
Ví dụ: Tìm từ lặp lại liên tiếp
import re s = 'Tahiti Tahiti Atoll' result = re.findall(r'\b(\w+)\b\s+\1\b', s) print(result) # ['Tahiti']
Giải thích: (\w+) bắt một từ vào group 1, \1 yêu cầu từ đó xuất hiện lại ngay sau khoảng trắng.
Ví dụ dùng trong re.sub (đổi tên file trùng)
import re text = 'file file name' # Thêm số thứ tự cho từ lặp result = re.sub(r'\b(\w+)\b\s+\1\b', r'\1_1 \1_2', text) print(result) # file_1 file_2 name