ซับนิพจน์/เมตาอักขระ “a| b” จับคู่ a หรือ b
ตัวอย่างที่ 1
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 p = Pattern.compile(regex);
Matcher m = p.matcher(input);
int count = 0;
while(m.find()) {
count++;
}
System.out.println("Number of matches: " + count);
}
}ผลลัพธ์
Number of matches: 2
ตัวอย่างที่ 2
โปรแกรม Java ต่อไปนี้อ่านค่าเพศจากผู้ใช้ และอนุญาตเฉพาะ M (ชาย), F(หญิง) หรือ O(อื่นๆ)
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexExample {
public static void main( String args[] ) {
// นิพจน์ปกติจับคู่ M หรือ F หรือ O
String regex = "M|F|O";
Scanner sc = new Scanner(System.in);
System.out.println("Enter students gender:");
String name = sc.nextLine();
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(name);
if(m.matches()) {
System.out.println("All OK");
} else {
System.out.println("Wrong Input");
}
}
}ผลลัพธ์ที่ 1
Enter students gender: M All OK
ผลลัพธ์ที่ 2
Enter students gender: male Wrong Input