MatchResult is an interface for representing the result of a match operation. This interface is implemented by the Matcher class. This interface contains query methods used to determine the results of a match against a regular expression. The match boundaries, groups, and group boundaries can only be retrieved but not modified through this interface. Here is a list of important methods provided in this interface:
Method Name |
Description |
int start() |
Returns the start index of the match in the input |
int start(int group) |
Returns the start index of the specified capturing group |
int end() |
Returns the offset after the last character matched |
int end(int group) |
Returns the offset after the last character of the subsequence captured by the given group during this match |
String group() |
Returns the input substring matched by the previous match |
String group(int group) |
Returns the input subsequence captured by the given group during the previous match operation |
int groupCount() |
Returns the number of capturing groups in this match result's pattern |
Let's take an example to understand this interface better.
Suppose, the input string is a web server response line from HTTP response headers:
HTTP/1.1 302 Found
Our regex pattern to parse this line is as follows:
HTTP/1.[01] (d+) [a-zA-Z]+
Note that there is only one captured group that captures integer status code.
Let's look at this code listing to understand the various methods of the MatchResult interface better:
package example.regex;
import java.util.regex.*;
public class MatchResultExample
{
public static void main(String[] args)
{
final String re = "HTTP/1\.[01] (\d+) [a-zA-Z]+";
final String str = "HTTP/1.1 302 Found";
final Pattern p = Pattern.compile(re);
Matcher m = p.matcher(str);
if (m.matches())
{
MatchResult mr = m.toMatchResult();
// print count of capturing groups
System.out.println("groupCount(): " + mr.groupCount());
// print complete matched text
System.out.println("group(): " + mr.group());
// print start position of matched text
System.out.println("start(): " + mr.start());
// print end position of matched text
System.out.println("end(): " + mr.end());
// print 1st captured group
System.out.println("group(1): " + mr.group(1));
// print 1st captured group's start position
System.out.println("start(1): " + mr.start(1));
// print 1st captured group's end position
System.out.println("end(1): " + mr.end(1));
}
}
}
We retrieve a MatchResult instance after calling the required Pattern and Matcher methods (discussed in the next section). After compiling and running the preceding code, we will get the following output, which shows the use of the various methods of this interface:
groupCount(): 1
group(): HTTP/1.1 302 Found
start(): 0
end(): 18
group(1): 302
start(1): 9
end(1): 12