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 上海狗狗训练基地
5 训练狗狗排便
6 狗狗基础训练
8 如何训练狗狗装死
9 狗狗站姿训练
10 狗狗训练用品
11 训练狗狗吧
12 狗狗要怎么训练
13 怎么训练狗狗玩球
14 训练狗狗唤回
15 狗狗训练躺下
16 狗狗训练指令
17 狗狗的训练技巧
18 狗狗不好训练