【发布时间】:2021-04-07 09:07:41
【问题描述】:
根据this question,find 和matches() 有很大的不同,仍然都以某种形式提供结果。
作为一种实用程序,toMatchResult 函数返回 matches() 操作的当前结果。我希望我在(1) 下的假设是有效的。 (正则表达式为here)
String line = "aabaaabaaabaaaaaab";
String regex = "(a*b)a{3}";
Matcher matcher = Pattern.compile(regex).matcher(line);
matcher.find();
// matcher.matches();(1) --> returns false because the regex doesn't match the whole string
String expectingAab = matcher.group(1);
System.out.println("actually: " + expectingAab);
不幸的是,以下方法根本不起作用(例外:未找到匹配项):
String line = "aabaaabaaabaaaaaab";
String regex = "(a*b)a{3}";
String expectingAab = Pattern.compile(regex).matcher(line).toMatchResult().group(1);
System.out.println("actually: " + expectingAab);
这是为什么呢?我的第一个假设是它不起作用,因为正则表达式应该匹配整个字符串;但是字符串值aabaaa 也会抛出相同的异常......
当然,匹配器需要使用find() 设置为正确的状态,但是如果我想使用oneliner 怎么办?我实际上为此实现了一个实用程序类:
protected static class FindResult{
private final Matcher innerMatcher;
public FindResult(Matcher matcher){
innerMatcher = matcher;
innerMatcher.find();
}
public Matcher toFindResult(){
return innerMatcher;
}
}
public static void main(String[] args){
String line = "aabaaabaaabaaaaaab";
String regex = "(a*b)a{3}";
String expectingAab = new FindResult(Pattern.compile(regex).matcher(line)).toFindResult().group(1);
System.out.println("actually: " + expectingAab);
}
我很清楚这不是创建 oneliner 的最佳解决方案,尤其是因为它给垃圾收集器带来了沉重的负担..
有没有更简单、更好的解决方案?
值得注意的是,我正在寻找解决方案 java8.匹配逻辑在 java 9 之上的工作方式不同。
【问题讨论】:
-
如果你不想创建新对象,为什么不直接使用静态方法呢?您不需要存储任何状态。你只是不喜欢
MatcherUtils.findResult(Pattern.compile("...").matcher("..."))这样的美学吗? -
这实际上是一个有效的观点!谢谢,如果没有内置功能,我也会接受这个答案。
标签: java regex java-8 one-liner