According to this question, there is a big difference between find
and matches()
, still both provide results in some form.
As a kind of Utility the toMatchResult
function returns with the current results of the matches()
operation. I hope my assumption under (1)
is valid. (regex is 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);
Unfortunately the following in no way works ( Exception: no match found ):
String line = "aabaaabaaabaaaaaab";
String regex = "(a*b)a{3}";
String expectingAab = Pattern.compile(regex).matcher(line).toMatchResult().group(1);
System.out.println("actually: " + expectingAab);
Why is that? My first assupmtion was that it doesn't work because the regex should match the whole string; but the same exceptio is being thrown with the string value aabaaa
as well...
Of course the matcher needs to be set to the correct state with find()
, but what if I'd like to use a oneliner for it? I actually implemented a utility calss for this:
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);
}
I know full well that this is not an optimal solution to create a oneliner, especially because it puts heavy loads to the garbage collector..
Is there an easier, better solution for this?
It's worth noting, that I'm looking for a solution java8. The matching logic works differently above java 9.