또는 논리 연산자 사용 | Java 정규 표현식의 경우 두 개의 주어진 표현식 중 하나를 일치시킬 수 있습니다.
예를 들어 정규 표현식이 둘 이상의 표현식과 일치해야 하는 경우 필수 표현식을 "|"로 구분하여 수행할 수 있습니다.
예시 1
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
public static void main(String args[]) {
//Reading String from user
System.out.println("Enter a String");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
//Regular expression to match string that starts with hello or ends with bye
String regex = "^hello|bye$";
//Compiling the regular expression
Pattern pattern = Pattern.compile(regex);
//Retrieving the matcher object
Matcher matcher = pattern.matcher(input);
if(matcher.find()) {
System.out.println("Match occurred");
} else {
System.out.println("Match not occurred");
}
}
} 출력 1
Enter a String hello how are you Match occurred
출력 2
Enter a String This is a sample string Match not occurred
예시 2
import java.util.Scanner;
public class RegexExample {
public static void main( String args[] ) {
//Regular expression to match either yes or no String regex = "yes|no";
System.out.println("Enter input value: ");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
boolean bool = input.matches(regex);
if(bool) {
System.out.println("match occurred");
} else {
System.out.println("match not accepted");
}
}
} 출력 1
Enter input value: yes match occurred
출력 2
Enter input value: hello match not accepted