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

Non-Capturing Groups ใน Java Regex

Capturing Groups** ใช้วงเล็บ () จัดกลุ่มตัวอักษรเป็นหน่วยเดียว เช่น (.*)(\\d+)(.*) มี 3 กลุ่ม

ผลการจับคู่ของแต่ละกลุ่มจะถูกเก็บไว้ สามารถดึงได้ด้วย group(1), group(2) เป็นต้น (group 0 = ทั้งหมด)

ตัวอย่าง Capturing Groups

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

public class CapturingGroups {
    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter input text");
        String input = sc.nextLine();
        String regex = "(.*)(\\d+)(.*)";
        
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(input);
        
        if (matcher.find()) {
            System.out.println("Found value: " + matcher.group(0));
            System.out.println("Found value: " + matcher.group(1));
            System.out.println("Found value: " + matcher.group(2));
            System.out.println("Found value: " + matcher.group(3));
        } else {
            System.out.println("NO MATCH");
        }
    }
}

ผลลัพธ์

Enter input text: sample data with 1234 (digits) in middle
Found value: sample data with 1234 (digits) in middle
Found value: sample data with 123
Found value: 4
Found value: (digits) in middle

Non-Capturing Groups

Non-capturing group ทำงานเหมือน capturing group แต่ ไม่เก็บผลลัพธ์ ใช้ (?:...) แทน (...)

เหมาะสำหรับ: จัดกลุ่มเพื่อใช้ quantifier หรือ alternation แต่ไม่ต้องการดึงค่ากลุ่มนั้น

ตัวอย่าง Non-Capturing Groups

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

public class CapturingGroups {
    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter input text");
        String input = sc.nextLine();
        // (?:\\d+) = non-capturing group
        String regex = "(.*)(?:\\d+)(.*)";
        
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(input);
        
        if (matcher.find()) {
            System.out.println("Found value: " + matcher.group(0));
            System.out.println("Found value: " + matcher.group(1));
            System.out.println("Found value: " + matcher.group(2));
        } else {
            System.out.println("NO MATCH");
        }
    }
}

ผลลัพธ์

Enter input text: sample data with 1234 (digits) in middle
Found value: sample data with 1234 (digits) in middle
Found value: sample data with 123
Found value: (digits) in middle

สรุปความแตกต่าง

(...)(?:...)
ประเภทSyntaxเก็บผลลัพธ์นับใน groupCount()
Capturingใช่ใช่
Non-capturingไม่ไม่

หมายเหตุ: Non-capturing group ไม่นับใน groupCount() และไม่สามารถอ้างอิงด้วย group(n) ได้