Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

Matcher groupCount() Method ใน Java พร้อมตัวอย่าง


คลาส java.util.regex.Matcher แทน engine ที่ดำเนินการจับคู่ต่างๆ ไม่มี constructor สำหรับคลาสนี้ คุณสามารถสร้าง/ได้รับ object ของคลาสนี้โดยใช้เมธอด matches() ของคลาส java.util.regex.Pattern

เมธอด groupCount() ของคลาส (Matcher) นี้คำนวณจำนวน capturing groups ในการจับคู่ปัจจุบัน

ตัวอย่างที่ 1: regex (.*)(\\d+)(.*) มี 3 groups

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class GroupTest {
    public static void main(String[] args) {
        String regex = "(.*)(\\d+)(.*)";
        String input = "This is a sample Text, 1234, with numbers in between.";
        
        // สร้าง Pattern object
        Pattern pattern = Pattern.compile(regex);
        
        // จับคู่ pattern ที่คอมไพล์แล้วใน String
        Matcher matcher = pattern.matcher(input);
        
        if (matcher.find()) {
            System.out.println("First group match: " + matcher.group(1));
            System.out.println("Second group match: " + matcher.group(2));
            System.out.println("Third group match: " + matcher.group(3));
            System.out.println("Number of groups capturing: " + matcher.groupCount());
        }
    }
}

Output

First group match: This is a sample Text, 123
Second group match: 4
Third group match: , with numbers in between.
Number of groups: 3

ตัวอย่างที่ 2: regex (t(\\S+)t)(\\s) มี 3 groups

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>.";
        // Regular expression to match contents of the bold tags
        String regex = "(t(\\S+)t)(\\s)";
        String str = "the words tit tat tweet tostff tact that tilt text start and end wit the letter t ";
        
        // สร้าง Pattern object
        Pattern pattern = Pattern.compile(regex);
        
        // จับคู่ pattern ที่คอมไพล์แล้วใน String
        Matcher matcher = pattern.matcher(str);
        
        while (matcher.find()) {
            System.out.println(matcher.group(0));
        }
        System.out.println("Total capturing groups: " + matcher.groupCount());
    }
}

Output

tit tat tweet tact that tilt text tart
Total capturing groups: 3