| |
e430. Searching and Replacing with Nonconstant Values Using a Regular Expression
The simplest way to replace all occurrences of a pattern in a
CharSequence 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
Matcher.appendReplacement() by converting all words that match
[a-zA-Z]+[0-9]+ to uppercase.
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
e429.
Quintessential Regular Expression Search and Replace Program
© 2002 Addison-Wesley.
| | |