子表达式/元字符“ a | b ”匹配a或b。
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 Nhooo";
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
以下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("输入学生的性别:");
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");
}
}
}输入学生的性别: M All OK
输入学生的性别: male Wrong Input