如何检查针对输入的多个正则表达式模式?使用 Java。
javaobject oriented programmingprogramming更新于 2025/2/9 1:48:17
"|"元字符: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("输入您的输入:");
String input = sc.nextLine();
//正则表达式
String regex = "\d{10}|^[aeiou]";
//创建一个 Pattern 对象
Pattern pattern = Pattern.compile(regex);
//创建一个 Matcher 对象
Matcher matcher = pattern.matcher(input);
if(matcher.find()) {
System.out.println(input+" is valid");
}else {
System.out.println(input+" is not valid");
}
}
}
输出 1
输入您的输入: 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 对象
另一种解决方案是使用单个 Pattern 对象编译所有正则表达式,并将它们添加到列表对象中,然后在输入文本中找到匹配项−
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("输入您的输入:");
String input = sc.nextLine();
//正则表达式
String regex1 = "\d{10}";
String regex2 = "^[aeiou]";
//创建一个 Pattern 对象
Pattern pattern1 = Pattern.compile(regex1);
Pattern pattern2 = Pattern.compile(regex2);
//创建 List 对象
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("对于正则表达式 "+pattern.pattern()+" "+input+" 有效");
} else {
System.out.println("对于正则表达式 "+pattern.pattern()+" "+input+" 是无效的");
}
}
}
}
输出 1
输入您的输入:
9848033228
对于正则表达式 \d{10},9848033228 有效
对于正则表达式 ^[aeiou],9848033228 是无效的
输出 2
输入您的输入:
an apple a day keeps doctor away
对于正则表达式 \d{10},an apple a day keeps doctor away is not valid 是无效的
对于正则表达式 ^[aeiou],an apple a day keeps doctor away 有效
相关文章
有用资源
java 参考教程 - 该教程包含有关 java 的更多信息:https://www.cainiaomax.com/java/

