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

Chương trình Java regex khớp dấu ngoặc đơn ( hoặc )


Regex khớp chuỗi chứa dấu ngoặc

"^.*[\\(\\)].*$"

Giải thích

  • ^ - đầu chuỗi
  • .* - 0 hoặc nhiều ký tự bất kỳ
  • [\\(\\)] - khớp '(' hoặc ')' (escape trong char class)
  • .* - 0 hoặc nhiều ký tự bất kỳ
  • $ - cuối chuỗi

Ví dụ 1: Dùng Pattern/Matcher

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

public class SampleTest {
    public static void main(String[] args) {
        String regex = "^.*[\\(\\)].*$";
        Scanner sc = new Scanner(System.in);
        System.out.println("Nhập dữ liệu: ");
        String input = sc.nextLine();
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(input);
        if (matcher.find()) {
            System.out.println("Input accepted");
        } else {
            System.out.println("Not accepted");
        }
    }
}
Nhập dữ liệu: sample(text) with parenthesis
Input accepted
Nhập dữ liệu: sample text
Not accepted

Ví dụ 2: Dùng String.matches()

import java.util.Scanner;

public class Example {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Nhập email: ");
        String email = sc.nextLine();
        String regex = "^.*[\\(\\)].*$";
        boolean result = email.matches(regex);
        System.out.println(result ? "Valid match" : "Invalid match");
    }
}

Mở rộng

Để khớp cặp ngoặc cân bằng (balanced parentheses), regex thông thường không đủ, cần dùng recursive pattern (PCRE) hoặc parser. Java regex không hỗ trợ recursive.