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

Java Regex: จับคู่วงเล็บ ( และ )

Regular Expression ที่รับสตริงที่มีวงเล็บ:

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

อธิบาย

  • ^ - เริ่มต้นสตริง
  • .* - ตัวอักษรใดๆ 0 หรือมากกว่า
  • [\\(\\)] - จับคู่ ( หรือ ) (ต้อง escape ด้วย \\)
  • $ - สิ้นสุดสตริง

ตัวอย่าง 1: ใช้ 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("Enter data: ");
        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");
        }
    }
}

ผลลัพธ์

Enter data: sample(text) with parenthesis
Input accepted

Enter data: sample text
Not accepted

ตัวอย่าง 2: ใช้ String.matches()

import java.util.Scanner;

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

ผลลัพธ์

Enter email address: sample(text) with parenthesis
Valid match

Enter email address: sample text
Invalid match

ข้อสังเกต

  • ใน Java string literal ต้อง escape backslash: \\( และ \\)
  • ใน regex pattern จริงคือ \(\)
  • String.matches() ต้องจับคู่ทั้งสตริง (เหมือนมี ^...$ ครอบ)
  • ตัวอย่าง 2 ใช้ชื่อตัวแปร e_mail แต่ regex ไม่ได้ validate email จริง แค่เช็ควงเล็บ