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

Comments

3 Sep 2010 - 2:13am by louis vuitton replica (not verified)

in the armani exchange watches fairway. chanel double c earrings

"With the ball in hand, dior replica jewelry it's much more important to louis vuitton ring hit the fairways," Woods said. vintage vivienne westwood shoes It was the first time louis vuitton graffiti tie since the 2006 British Open juicy couture clothes at Royal Liverpool that he anna sui clothing hit his 3-wood off the cc jewellery tee on every par

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.