Phần biểu thức/metaký tự “a|b” khớp với a hoặc b.
Ví dụ 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("Số lần khớp: " + count);
}
}
Kết quả
Số lần khớp: 2
Ví dụ 2
Chương trình Java sau đọc giá trị giới tính từ người dùng và chỉ cho phép M (nam), F (nữ) hoặc O (khác).
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexExample {
public static void main(String args[]) {
// Biểu thức chính quy khớp M hoặc F hoặc O
String regex = "M|F|O";
Scanner sc = new Scanner(System.in);
System.out.println("Nhập giới tính học sinh:");
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");
}
}
}
Kết quả 1
Nhập giới tính học sinh: M All OK
Kết quả 2
Nhập giới tính học sinh: male Wrong Input