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

Logical Operators ใน Java Regex

Java Regex รองรับ logical operators 3 แบบ:

  • XY - X ตามด้วย Y (Concatenation)
  • X|Y - X หรือ Y (Alternation)
  • (X) - Capturing Group

1. XY: X ตามด้วย Y (Concatenation)

จับคู่ตัวอักษร/รูปแบบติดกัน

String regex = "am";
```
จับคู่ "am" ใน "sample" แต่ไม่จับคู่ใน "hello"

2. X|Y: X หรือ Y (Alternation)

จับคู่ ใดๆ หนึ่ง ระหว่าง X และ Y

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

public class RegexExample {
    public static void main(String args[]) {
        String regex = "Hello|welcome";
        String input = "Hello how are you welcome to Tutorialspoint";
        
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(input);
        int count = 0;
        while (matcher.find()) {
            count++;
        }
        System.out.println("Number of matches: " + count);
    }
}

ผลลัพธ์

Number of matches: 2

3. (X): Capturing Group

จัดกลุ่มตัวอักษรเป็นหน่วยเดียว ใช้วงเล็บ ()

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

สรุป

Operatorชื่อฟังก์ชันตัวอย่าง
XYConcatenationX ตามด้วย Yab จับคู่ "ab"
X|YAlternationX หรือ Ycat|dog จับคู่ cat หรือ dog
(X)Capturing Groupจัดกลุ่ม X(\d+) จับคู่ตัวเลขเป็นกลุ่ม

หมายเหตุ

  • Alternation | มี precedence ต่ำสุด ใช้วงเล็บควบคุม: (cat|dog)food
  • Non-capturing group: (?:X) จัดกลุ่มแต่ไม่ capture