Java中的正则表达式a | b元字符
子表达式/元字符“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 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
例子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");
}
}
}输出1
输入学生的性别: M All OK
输出2
输入学生的性别: male Wrong Input
热门推荐
1 如何训练狗狗不叫
2 训练狗狗不叫
3 训练狗狗随行
4 怎么训练狗狗不叫
7 训练比熊狗狗教程
10 上海狗狗训练
11 怎么训练狗狗上厕所
12 训练狗狗趴下
13 狗狗服从训练
14 训练狗狗拒食
15 训练狗狗笑
16 训练狗狗大便
17 训练狗狗立
18 训练狗狗捡东西