하위 표현식/메타 문자 “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
다음 자바 프로그램은 사용자로부터 성별 값을 읽어오는데 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