import java.util.regex.*; import java.io.*; public class IndicesOfGroupOfText{ public static void main(String[] args){ 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(); System.out.println("Complete string/text: " + inputStr); int a = 0; if(matchFound){ // Get all groups for this match for(int i=0; i<=matcher.groupCount(); i++){ a = a + 1; // Get the group's captured text String groupStr = matcher.group(i); System.out.println(groupStr); // Get the group's indices int groupStart = matcher.start(i); int groupEnd = matcher.end(i); System.out.println("Last index of the group of \'" + groupStr + "\': " + groupStart + " " + (groupEnd-1)); // groupStr is equivalent to inputStr.subSequence(groupStart, groupEnd); } } if (a == 0){ System.out.println("No match found."); System.exit(0); } } }