如何使用 Java RegEx 匹配两个给定表达式之一?

javaobject oriented programmingprogramming更新于 2024/5/5 7:08:17

使用 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("输入字符串");
      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("匹配发生");
      } else {
         System.out.println("未匹配");
      }
   }
}

输出 1

输入一个字符串
hello how are you
匹配发生

输出 2

输入一个字符串
这是一个示例字符串
未发生匹配

示例 2

import java.util.Scanner;
public class RegexExample {
   public static void main( String args[] ) {
      //匹配是或否的正则表达式 String regex = "yes|no";
      System.out.println("输入输入值:");
      Scanner sc = new Scanner(System.in);
      String input = sc.nextLine();
      boolean bool = input.matches(regex);
      if(bool) {
         System.out.println("匹配发生");
      } else {
         System.out.println("匹配不被接受");
      }
   }
}

输出 1

输入输入值:
yes
匹配发生

输出 2

输入输入值:
hello
匹配不被接受

相关文章


有用资源