Phương thức groupCount()
matcher.groupCount() trả về số lượng capturing groups trong regex của match hiện tại.
Ví dụ
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
public static void main(String[] args) {
String str = "the words tit tat tweet tostff tact that tilt text. start and end with the letter t";
String regex = "(t(\\S+)t)(\\s)";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(str);
while (matcher.find()) {
System.out.println(matcher.group(0));
}
System.out.println("Tổng capturing groups: " + matcher.groupCount());
}
}
Kết quả
tit
tat
tweet
tact
that
tilt
text
tart
Tổng capturing groups: 3
Giải thích regex (t(\\S+)t)(\\s)
- Group 1:
(t(\\S+)t)- từ bắt đầu và kết thúc bằng 't', giữa là non-whitespace - Group 2:
(\\S+)- phần giữa (nested trong group 1) - Group 3:
(\\s)- khoảng trắng sau từ
Lưu ý
- Chỉ đếm capturing groups (ngoặc đơn thường). Non-capturing
(?:...)không đếm. - Group 0 (toàn bộ match) không tính trong groupCount().
- Dùng để validate cấu trúc regex động.