Getting the Indices of a Matching Group in a Regular Expression

For more information about groups, see Capturing Text in a Group in a Regular Expression.
CharSequence inputStr = "abbabcd"; String patternStr = "(a(b*))+(c*)"; // Compile and use regular expression Pattern pattern = Pattern.compile(patternStr); Matcher matcher = pattern.matcher(inputStr); boolean matchFound = matcher.find(); if (matchFound) { // Get all groups for this match for (int i=0; i<=matcher.groupCount(); i++) { // Get the group's captured text String groupStr = matcher.group(i); // Get the group's indices int groupStart = matcher.start(i); int groupEnd = matcher.end(i); // groupStr is equivalent to inputStr.subSequence(groupStart, groupEnd); } }

Post a comment

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image. Ignore spaces and be careful about upper and lower case.