Java 中的正则表达式 a|b 元字符
javaobject oriented programmingprogramming更新于 2024/5/2 22:36:17
子表达式/元字符"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";
模式 p = Pattern.compile(regex);
匹配器 m = p.matcher(input);
int count = 0;
while(m.find()) {
count++;
}
System.out.println("匹配数:"+count);
}
}
输出
匹配数: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("输入学生性别:");
String name = sc.nextLine();
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(name);
if(m.matches()) {
System.out.println("全部 OK");
} else {
System.out.println("输入错误");
}
}
}
输出 1
输入学生性别: M 全部 OK
输出 2
输入学生性别: male 输入错误
相关文章
有用资源
java 参考教程 - 该教程包含有关 java 的更多信息:https://www.cainiaomax.com/java/

