![]() |
The Java Developers Almanac 1.4Order this book from Amazon. |
e437. Getting the Indices of a Matching Group in a Regular ExpressionFor more information about groups, see e436 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); } }
e438. Using a Non-Capturing Group in a Regular Expression e439. Using the Captured Text of a Group within a Pattern e440. Using the Captured Text of a Group within a Replacement Pattern
© 2002 Addison-Wesley. |