สามารถจัดกลุ่มตัวอักษรหลายตัวเป็นหน่วยเดียวได้ด้วยวงเล็บ () เรียกว่า Capturing Groups
ใช้เมธอด groupCount() ของคลาส Matcher เพื่อนับจำนวน capturing groups ใน pattern ปัจจุบัน
ตัวอย่าง
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
public static void main(String[] args) {
String str1 = "<p>This <b>is</b> an <b>example</b> HTML <b>script</b> where <b>ever</b> alternative <b>word</b> is <b>bold</b></p>.";
// Regex สำหรับจับคู่เนื้อหาในแท็ก bold
String regex = "(t(\\S+)t)(\\s)";
String str = "the words tit tat tweet tostff tact that tilt text. start and end with the letter t";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(str);
while (matcher.find()) {
System.out.println(matcher.group(0));
}
System.out.println("Total capturing groups: " + matcher.groupCount());
}
}
ผลลัพธ์
tit
tat
tweet
tact
that
tilt
text
tart
Total capturing groups: 3
อธิบาย
- Regex
(t(\\S+)t)(\\s)มี 3 capturing groups:(t(\\S+)t)- กลุ่มนอกสุด(\\S+)- กลุ่มใน (non-whitespace 1+ ตัว)(\\s)- whitespace 1 ตัว
groupCount()คืนค่า 3 (ไม่นับ group 0)- Non-capturing groups
(?:...)ไม่นับใน groupCount()
การนับกลุ่ม
กลุ่มนับตามลำดับวงเล็บเปิด ( จากซ้ายไปขวา:
((A)(B)) → Group 1: (A)(B), Group 2: A, Group 3: B