Dùng ngoặc đơn () để nhóm một phần của regex, áp dụng toán tử (quantifier, alternation) cho cả nhóm.
Capturing Group & Backreference
Ngoặc đơn tạo capturing group — phần chuỗi khớp được lưu lại để dùng sau (backreference \1, \2... hoặc $1 trong replacement).
Ví dụ: Tìm từ lặp lại
import re s = 'Tahiti Tahiti Atoll' result = re.findall(r'\b(\w+)\b\s+\1\b', s) print(result) # ['Tahiti']
Pattern \b(\w+)\b\s+\1\b:
(\w+)— group 1: một từ.\s+— khoảng trắng.\1— backreference: đúng từ vừa bắt được.
Ví dụ: findall với group
import re s = 'Tahiti $% Tahiti *&^ 34 Atoll' result = re.findall(r'(\w+)', s) print(result) # ['Tahiti', 'Tahiti', '34', 'Atoll']
findall trả về nội dung capturing group thay vì toàn bộ match khi pattern có group.