English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java RegEx를 사용하여 두 가지 표현식 중 하나를 어떻게 일치시키는가?

또는 논리 연산자 '|'를 사용하여 두 가지 표현식 중 하나를 매칭할 수 있는 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[]) {
      //사용자로부터 문자열을 읽습니다
      System.out.println("Enter a String");
      Scanner sc = new Scanner(System.in);
      String input = sc.nextLine();
      //정규 표현식은 hello로 시작하거나 bye로 끝나는 문자열을 매칭합니다
      String regex = "^hello|bye$";
      //정규 표현식을 컴파일
      Pattern pattern = Pattern.compile(regex);
      //검색 매칭 객체
      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[] ) {
      //정규 표현식을 매칭하려면 yes 또는 no 문자열 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
좋아할 만한 것