After a successful match using the find() method, you can use its start() and end() methods to know the match boundary for groups.
These methods are overloaded:
int start() int start(int groupNumber) int start(String groupName) int end() int end(int groupNumber) int end(String groupName)
The following code prints the start of each group for each successful match.
import java.util.regex.Matcher; import java.util.regex.Pattern; public class Main { public static void main(String[] args) { // Prepare the regular expression String regex = "\\b(?<areaCode>\\d{3})(?<prefix>\\d{3})(?<lineNumber>\\d{4})\\b"; String source = "1234567890, 1234567, and 1234567890"; System.out.println("Source Text: " + source); // Compile the regular expression Pattern p = Pattern.compile(regex); // Get Matcher object Matcher m = p.matcher(source); while (m.find()) { String matchedText = m.group(); int start1 = m.start("areaCode"); int start2 = m.start("prefix"); int start3 = m.start("lineNumber"); System.out.print("Matched Text:" + matchedText); System.out.print(". Area code start:" + start1); System.out.print(", Prefix start:" + start2); System.out.println(", Line Number start:" + start3); }/*from ww w .j ava 2 s .c om*/ } }