Course contentsShow
← Java
Lesson 2250 of 2,87044. Regular ExpressionsFree lesson

Accessing Match Results: start(), end(), group()

Retrieving match positions with start() and end(), and the matched text with group() after a successful find().

Accessing Match Results: start(), end(), group()

You'll learn how to retrieve detailed information about a successful regex match, including its position and text.

The Core Idea

Once find() returns true, your Matcher object holds information about what it found. You can ask it where the match occurred and what text was matched. Think of it like highlighting text in a document—you want to know both the highlight's location and the actual words highlighted.

Three Essential Methods

After a successful find(), these methods give you match details:

start() – Where the Match Begins

Returns the index of the first character in the matched substring. This is the position where your match starts within the input string.

end() – Where the Match Ends

Returns the index after the last character of the match. It follows Java's standard "end index is exclusive" convention, making it perfect for substring(start, end) operations.

group() – The Matched Text

Returns the actual substring that matched your pattern. This is the text itself that satisfied your regex.

Putting It Together

import java.util.regex.*;

Pattern pattern = Pattern.compile("\\d+");
Matcher matcher = pattern.matcher("Order 123 and Order 456");

while (matcher.find()) {
    System.out.println("Match: " + matcher.group());
    System.out.println("Start: " + matcher.start());
    System.out.println("End: " + matcher.end());
    System.out.println("---");
}

Output:

Match: 123
Start: 6
End: 9
---
Match: 456
Start: 20
End: 23
---

Key Takeaway: After a successful find(), use group() to get the matched text, start() for its starting position, and end() for the position just after it—essential for extracting and locating regex matches in your input.