Khái niệm
Named capturing groups cho phép tham chiếu nhóm khớp bằng tên thay vì số thứ tự. Java hỗ trợ từ SE 7.
Cú pháp: (?<tên>pattern)
Ví dụ: Phân tích số điện thoại
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ReplaceAll {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Nhập văn bản: ");
String input = sc.nextLine();
// Định dạng: 91-08955-224558
String regex = "(?<globalCode>[\\d]{2})-(?<nationalCode>[\\d]{5})-(?<number>[\\d]{6})";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input);
while (matcher.find()) {
System.out.println("Global code: " + matcher.group("globalCode"));
System.out.println("National code: " + matcher.group("nationalCode"));
System.out.println("Phone number: " + matcher.group("number"));
}
}
}
Kết quả
Nhập văn bản: 91-08955-224558
Global code: 91
National code: 08955
Phone number: 224558
Lợi ích
- Code dễ đọc, dễ bảo trì hơn dùng số nhóm (group(1), group(2)...)
- Thay đổi regex không ảnh hưởng index nhóm khác
- Hữu ích khi regex phức tạp có nhiều nhóm
Các phương thức liên quan
matcher.group(String name)- lấy nội dung nhóm theo tênmatcher.start(String name),end(String name)- vị trí nhóm