将字符串与多个正则表达式模式匹配

2022-09-01 18:12:20

我有一个输入字符串。

我正在考虑如何有效地将此字符串与多个正则表达式进行匹配。

Example Input: ABCD

我想与这些 reg-ex 模式进行匹配,如果其中至少有一个匹配,则返回:true

[a-zA-Z]{3}

^[^\\d].*

([\\w&&[^b]])*

我不确定如何一次匹配多个模式。有人能告诉我我们如何有效地做到这一点吗?


答案 1

如果您只有几个正则表达式,并且在编译时它们都是已知的,那么这就足够了:

private static final Pattern
  rx1 = Pattern.compile("..."),
  rx2 = Pattern.compile("..."),
  ...;

return rx1.matcher(s).matches() || rx2.matcher(s).matches() || ...;

如果它们更多,或者它们在运行时加载,请使用模式列表:

final List<Pattern> rxs = new ArrayList<>();


for (Pattern rx : rxs) if (rx.matcher(input).matches()) return true;
return false;

答案 2

您可以从单个正则表达式中创建一个大型正则表达式:

[a-zA-Z]{3}|^[^\\d].*|([\\w&&[^b]])*