如何用 Java 检查输入中的多个正则表达式?


“|” 元字符:Java 正则表达式中的元字符 “|” 允许你匹配多个正则表达式,比如,如果你需要用多个表达式匹配某段输入文本,你需要用它将它们分隔开,比如

exp1|exp2|exp3

示例

 在线演示

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class SampleExample {
   public static void main(String[] args) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter your input: ");
      String input = sc.nextLine();
      //Regular expression
      String regex = "\d{10}|^[aeiou]";
      //Creating a pattern object
      Pattern pattern = Pattern.compile(regex);
      //Creating a Matcher object
      Matcher matcher = pattern.matcher(input);
      if(matcher.find()) {
         System.out.println(input+" is valid");
      }else {
         System.out.println(input+" is not valid");
      }
   }
}

输出 1

Enter your input:
9848033228
9848033228 is valid

输出 2

Enter your input:
an apple a day keeps doctor away
an apple a day keeps doctor away is valid

使用列表对象

另一个解决方案是使用单个模式对象编译所有正则表达式,并将它们添加到一个列表对象中,然后在输入文本中查找匹配项,如下所示:

List list = new ArrayList<>();
list.add(Pattern.compile(regex1));
list.add(Pattern.compile(regex2));
for (Pattern pattern: list) {
   Matcher matcher = pattern.matcher(input);
   if(matcher.find()) {
      . . . . . . . . . . . . . . .
   }else {
      . . . . . . . . . . . . . . .
   }
}

示例

 在线演示

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MultipleRegex {
   public static void main(String[] args) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter your input: ");
      String input = sc.nextLine();
      //Regular expressions
      String regex1 = "\d{10}";
      String regex2 = "^[aeiou]";
      //Creating a pattern objects
      Pattern pattern1 = Pattern.compile(regex1);
      Pattern pattern2 = Pattern.compile(regex2);
      //Creating an List object
      List<Pattern> patterns = new ArrayList<>();
      patterns.add(pattern1);
      patterns.add(pattern2);
      for (Pattern pattern: patterns) {
         Matcher matcher = pattern.matcher(input);
         if(matcher.find()) {
            System.out.println("For regex "+pattern.pattern()+" "+input+" is valid");
         } else {
            System.out.println("For regex "+pattern.pattern()+" "+input+" is not valid");
         }
      }
   }
}

输出 1

Enter your input:
9848033228
For regex \d{10} 9848033228 is valid
For regex ^[aeiou] 9848033228 is not valid

输出 2

Enter your input:
an apple a day keeps doctor away
For regex \d{10} an apple a day keeps doctor away is not valid
For regex ^[aeiou] an apple a day keeps doctor away is valid

更新于: 2020 年 1 月 10 日

5K+ 浏览

开启您的职业生涯

完成课程,获得认证

开始
广告
© . All rights reserved.