![]() |
The Java Developers Almanac 1.4Order this book from Amazon. |
e430. Searching and Replacing with Nonconstant Values Using a Regular ExpressionThe simplest way to replace all occurrences of a pattern in aCharSequence is to use Matcher.replaceAll() . However, this method
is restricted to replacement values that are constant. If the
replacement value is dynamic (e.g., converting the match to
uppercase), Matcher.appendReplacement() must be used.
This example demonstrates the use of
CharSequence inputStr = "ab12 cd efg34"; String patternStr = "([a-zA-Z]+[0-9]+)"; // Compile regular expression Pattern pattern = Pattern.compile(patternStr); Matcher matcher = pattern.matcher(inputStr); // Replace all occurrences of pattern in input StringBuffer buf = new StringBuffer(); boolean found = false; while ((found = matcher.find())) { // Get the match result String replaceStr = matcher.group(); // Convert to uppercase replaceStr = replaceStr.toUpperCase(); // Insert replacement matcher.appendReplacement(buf, replaceStr); } matcher.appendTail(buf); // Get result String result = buf.toString(); // AB12 cd EFG34
© 2002 Addison-Wesley. |