Interface java.util.regex.MatchResult เมธอด groupCount() นับและคืนจำนวน capturing groups ใน regular expression ของ object ปัจจุบัน
ตัวอย่าง
import java.util.Scanner;
import java.util.regex.MatchResult;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class GroupCount {
public static void main(String args[]) {
String regex = "(.*)(\\d+)(.*)";
Scanner sc = new Scanner(System.in);
System.out.println("Enter input text: ");
String input = sc.nextLine();
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input);
if (matcher.find()) {
System.out.println("Match found");
}
MatchResult res = matcher.toMatchResult();
int count = res.groupCount();
System.out.println("No.of groups: " + count);
}
}
ผลลัพธ์
Enter input text: This is a sample Text, 123
Match found
No.of groups: 3
อธิบาย
- Regex
(.*)(\\d+)(.*)มี 3 capturing groups:(.*)- กลุ่มแรก(\\d+)- กลุ่มที่สอง(.*)- กลุ่มที่สาม
groupCount()คืน 3 (ไม่นับ group 0)MatchResultจากmatcher.toMatchResult()เป็น snapshot ของ match state
Group Counting Rules
- นับเฉพาะ capturing groups
(...) - ไม่รวม non-capturing groups
(?:...) - ไม่รวม group 0 (entire match)
- นับตามลำดับวงเล็บเปิด
(จากซ้ายไปขวา
ตัวอย่างเปรียบเทียบ
| Regex | groupCount() | Groups |
|---|---|---|
(a)(b)(c) | 3 | 1:a, 2:b, 3:c |
(a(?:b)c) | 1 | 1:abc (?:b) ไม่นับ |
((a)(b)) | 3 | 1:(ab), 2:a, 3:b |
a(b)c | 1 | 1:b |
abc | 0 | (ไม่มีวงเล็บ) |
การใช้งาน
เหมาะสำหรับ: dynamic regex processing, validation ว่า pattern มีกลุ่มกี่กลุ่ม, generic extraction logic