我有一个输入字符串。
我在思考如何有效地将此字符串与多个正则表达式匹配。
Example Input: ABCD
我想针对这些正则表达式进行匹配,并在其中至少有一个匹配时返回true
:
[a-zA-Z]{3}
^[^\\d].*
([\\w&&[^b]])*
我不确定如何一次匹配多个模式。有人能告诉我我们如何有效地做到这一点吗?
如果你只有几个正则表达式,并且它们在编译时都已知,那么这就足够了:
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;
[a-zA-Z]{3}|^[^\\d].*|([\\w&&[^b]])*
group()
方法确定哪个匹配,但是你必须为每个组查询它。最好使用单独的正则表达式和一堆if else语句。 - vandale就像在(在字符串上运行多个正则表达式模式)中所解释的那样,最好将每个正则表达式连接成一个大的正则表达式,然后仅运行匹配器一次。如果您经常重复使用正则表达式,则这是一项很大的改进。
private static HashMap<String, String> regs = new HashMap<String, String>();
...
regs.put("COMMA", ",");
regs.put("ID", "[a-z][a-zA-Z0-9]*");
regs.put("SEMI", ";");
regs.put("GETS", ":=");
regs.put("DOT", "\\.");
for (HashMap.Entry<String, String> entry : regs.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
Matcher m = Pattern.compile(value).matcher("program var a, b, c; begin a := 0; end.");
boolean f = m.find();
while(f)
{
System.out.println(key);
System.out.print(m.group() + " ");
System.out.print(m.start() + " ");
System.out.println(m.end());
f = m.find();
}
}
}
private static Matcher m1 = Pattern.compile("regex1").matcher("");
private static Matcher m2 = Pattern.compile("regex2").matcher("");
private static Matcher m3 = Pattern.compile("regex3").matcher("");
public boolean matchesAtLeastOneRegex(String input) {
return m1.reset(input).matches()
|| m2.reset(input).matches()
|| m3.reset(input).matches();
}
Matcher
的存在目的是每次创建它以维护单个匹配操作的状态。你的代码不是线程安全的。 - Marko Topolnik我不确定 effectively
是什么意思,但如果它涉及性能并且您想检查很多字符串,我会选择这个。
...
static Pattern p1 = Pattern.compile("[a-zA-Z]{3}");
static Pattern p2 = Pattern.compile("^[^\\d].*");
static Pattern p3 = Pattern.compile("([\\w&&[^b]])*");
public static boolean test(String s){
return p1.matcher(s).matches ? true:
p2.matcher(s).matches ? true:
p3.matcher(s).matches;
}
我不确定它会如何影响性能,但是使用|
将它们全部组合在一个正则表达式中也可能有所帮助。
p1.matcher(s).matches() || p2.matcher(s).matches() || p3.matcher(s).matches()
呢? - kratenko
return rx1.matcher(s).matches() || rx2.matcher(s).matches() || ...;
可以翻译为:如果字符串s
匹配正则表达式rx1
、rx2
或其他正则表达式,则返回 true。 - Marko Topolnik