THE Java™ Programming Language, Fourth Edition

(Jeff_L) #1
Replaces the first occurrence of this matcher's pattern with the replacement
string, returning the result. The matcher is first reset and is not reset after the
operation.

public StringreplaceAll(String replacement)

Replaces all occurrences of this matcher's pattern with the replacement string,
returning the result. The matcher is first reset and is not reset after the
operation.

public MatcherappendReplacement(StringBuffer buf, String
replacement)

Adds to the string buffer the characters between the current append and
match positions, followed by the replacement string, and then moves the
append position to be after the match. As shown above, this can be used as
part of a replacement loop. Returns this matcher.

public StringBufferappendTail(StringBuffer buf)

Adds to the string buffer all characters from the current append position until
the end of the sequence. Returns the buffer.

So the previous example can be written more simply with replaceAll:


Pattern pat = Pattern.compile("sun");
Matcher matcher = pat.matcher(input);
String result = matcher.replaceAll("moon");


As an example of a more complex usage of regular expressions, here is code that will replace every number
with the next largest number:


Pattern pat = Pattern.compile("[-+]?[0-9]+");
Matcher matcher = pat.matcher(input);
StringBuffer result = new StringBuffer();
boolean found;
while ((found = matcher.find())) {
String numStr = matcher.group();
int num = Integer.parseInt(numStr);
String plusOne = Integer.toString(num + 1);
matcher.appendReplacement(result, plusOne);
}
matcher.appendTail(result);


Here we decode the number found by the match, add one to it, and replace the old value with the new one.


The replacement string can contain a $g, which will be replaced with the value from the gth capturing group
in the expression. The following method uses this feature to swap all instances of two adjacent words:


public static String
swapWords(String w1, String w2, String input)
{
String regex = "\b(" + w1 + ")(\W+)(" + w2 + ")\b";
Pattern pat = Pattern.compile(regex);

Free download pdf