正则表达式 a|b 元字符在 Java 中
子表达式/元字符“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[] ) {
//Regular expression to match M or, F or, 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
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP