将字符串与多个正则表达式模式匹配 [英] Match a string against multiple regex patterns

查看:154
本文介绍了将字符串与多个正则表达式模式匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个输入字符串。

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

I am thinking how to match this string against more than one regular expression effectively.

Example Input: ABCD

我是喜欢匹配这些注册模式,并返回 true 如果其中至少有一个匹配:

I'd like to match against these reg-ex patterns, and return true if at least one of them matches:

[a-zA-Z]{3}

^[^\\d].*

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

我不确定如何与多个匹配模式一下子。有人可以告诉我我们如何有效地做到这一点?

I am not sure how to match against multiple patterns at once. Can some one tell me how do we do it effectively?

推荐答案

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

If you have just a few regexes, and they are all known at compile time, then this can be enough:

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

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

如果有更多这些,或者它们是在运行时加载的,那么使用模式列表:

If there are more of them, or they are loaded at runtime, then use a list of patterns:

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


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

这篇关于将字符串与多个正则表达式模式匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆