The MatchResult interface allows PatternMatcher implementors to return
results storing match information in whatever format they like, while
presenting a consistent way of accessing that information. However,
MatchResult implementations should strictly follow the behavior
described for the interface methods.
A MatchResult instance contains a pattern match and its saved groups.
You can access the entire match directly using the
group(int) method with an argument of 0,
or by the toString() method which is
defined to return the same thing. It is also possible to obtain
the beginning and ending offsets of a match relative to the input
producing the match by using the
beginOffset(int) and endOffset(int) methods. The
begin(int) and end(int) are useful in some
circumstances and return the begin and end offsets of the subgroups
of a match relative to the beginning of the match.
You might use a MatchResult as follows:
int groups;
PatternMatcher matcher;
PatternCompiler compiler;
Pattern pattern;
PatternMatcherInput input;
MatchResult result;
compiler = new Perl5Compiler();
matcher = new Perl5Matcher();
try {
pattern = compiler.compile(somePatternString);
} catch(MalformedPatternException e) {
System.out.println("Bad pattern.");
System.out.println(e.getMessage());
return;
}
input = new PatternMatcherInput(someStringInput);
while(matcher.contains(input, pattern)) {
result = matcher.getMatch();
// Perform whatever processing on the result you want.
// Here we just print out all its elements to show how its
// methods are used.
System.out.println("Match: " + result.toString());
System.out.println("Length: " + result.length());
groups = result.groups();
System.out.println("Groups: " + groups);
System.out.println("Begin offset: " + result.beginOffset(0));
System.out.println("End offset: " + result.endOffset(0));
System.out.println("Saved Groups: ");
// Start at 1 because we just printed out group 0
for(int group = 1; group < groups; group++) {
System.out.println(group + ": " + result.group(group));
System.out.println("Begin: " + result.begin(group));
System.out.println("End: " + result.end(group));
}
}
A MatchResult instance contains a pattern match and its saved groups. You can access the entire match directly using the group(int) method with an argument of 0, or by the toString() method which is defined to return the same thing. It is also possible to obtain the beginning and ending offsets of a match relative to the input producing the match by using the beginOffset(int) and endOffset(int) methods. The begin(int) and end(int) are useful in some circumstances and return the begin and end offsets of the subgroups of a match relative to the beginning of the match.
You might use a MatchResult as follows: