java 多个正则表达式_如何针对一个输入检查多个正则表达式模式?使用Java。

“ |” meta字符: meta字符“ |” 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();

//正则表达式

String regex = "\\d{10}|^[aeiou]";

//创建一个模式对象

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");

}

}

}

输出1Enter your input:

9848033228

9848033228 is valid

输出2Enter your input:

an apple a day keeps doctor away

an apple a day keeps doctor away is valid

使用列表对象

另一个解决方案是使用单个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("Enter your input: ");

String input = sc.nextLine();

//正则表达式s

String regex1 = "\\d{10}";

String regex2 = "^[aeiou]";

//创建一个模式对象s

Pattern pattern1 = Pattern.compile(regex1);

Pattern pattern2 = Pattern.compile(regex2);

//创建一个列表对象

List 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");

}

}

}

}

输出1Enter your input:

9848033228

For regex \d{10} 9848033228 is valid

For regex ^[aeiou] 9848033228 is not valid

输出2Enter 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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值