โดยใช้ตัวดำเนินการ OR ลอจิก | ของนิพจน์ปกติ Java คุณสามารถจับคู่ได้ทั้งสองนิพจน์ที่กำหนด
เช่น หากคุณต้องการให้นิพจน์ปกติจับคู่กับนิพจน์มากกว่าหนึ่งนิพจน์ สามารถทำได้โดยคั่นนิพจน์ที่ต้องการด้วย “|”
ตัวอย่างที่ 1
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
public static void main(String args[]) {
// อ่านสตริงจากผู้ใช้
System.out.println("Enter a String");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
// นิพจน์ปกติจับคู่สตริงที่เริ่มด้วย hello หรือจบด้วย bye
String regex = "^hello|bye$";
// คอมไพล์นิพจน์ปกติ
Pattern pattern = Pattern.compile(regex);
// ดึงออบเจ็กต์ matcher
Matcher matcher = pattern.matcher(input);
if(matcher.find()) {
System.out.println("Match occurred");
} else {
System.out.println("Match not occurred");
}
}
}ผลลัพธ์ที่ 1
Enter a String hello how are you Match occurred
ผลลัพธ์ที่ 2
Enter a String This is a sample string Match not occurred
ตัวอย่างที่ 2
import java.util.Scanner;
public class RegexExample {
public static void main( String args[] ) {
// นิพจน์ปกติจับคู่ yes หรือ no
String regex = "yes|no";
Scanner sc = new Scanner(System.in);
System.out.println("Enter input value: ");
String input = sc.nextLine();
boolean bool = input.matches(regex);
if(bool) {
System.out.println("match occurred");
} else {
System.out.println("match not accepted");
}
}
}ผลลัพธ์ที่ 1
Enter input value: yes match occurred
ผลลัพธ์ที่ 2
Enter input value: hello match not accepted