Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Toán tử Logic trong Java Regular Expressions


3 Toán tử Logic

  1. XY - X theo sau Y (concatenation)
  2. X|Y - X hoặc Y (alternation)
  3. (X) - Capturing group

1. XY: X theo sau Y

Khớp hai ký tự liên tiếp.

String regex = "am";
// "sample text" -> khớp "am" trong "sample"
// "hello how are you" -> không khớp

2. X|Y: X hoặc Y

Khớp một trong hai biểu thức.

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("Số khớp: " + count); // 2
    }
}

3. (X): Capturing Group

Nhóm ký tự thành đơn vị, lưu kết quả để truy xuất sau.

String regex = "(.*)(\\d+)(.*)";
Input: "sample data with 1234 (digits) in middle"
Group 0: sample data with 1234 (digits) in middle
Group 1: sample data with 123
Group 2: 4
Group 3: (digits) in middle

Ứng dụng thực tế

  • |: Validate nhiều định dạng (email|phone|url)
  • (): Extract phần cần thiết (date groups: (\\d{4})-(\\d{2})-(\\d{2}))
  • Kết hợp: (cat|dog) khớp "cat" hoặc "dog" như một unit