XML technologies / Regular expressions / Java / The Matcher object / search and replace in detail

(Excerpt from "Regular expressions" by Jeffrey E. F. Friedl)

Two further methods expose the Matcher object’s search-and-replace machinery. They build a result string in a supplied StringBuffer . The first is called after each match to append the replacement and intervening text. The second is called after all matches to append the remaining tail.

 

Matcher appendReplacement(StringBuffer resultat, String ersatztext)

Called immediately after a successful match using find, it appends two strings to the supplied StringBuffer: the input text before the match, then the ersatztext processed as described above.

Suppose Matcher m connects the regex ˹\w+˼ to input string ›-->ein+Test<--‹. On the first iteration of while

while (m.find())
    m.appendReplacement(sb, "XXX")

, method find finds the underlined portion in ‘-->ein+Test<--’.

Calling appendReplacement first appends to the StringBuffer sb the preceding text, ‘-->’. The match itself is skipped, and replacement ‘XXX’ is appended to sb.

On the second iteration, find finds ‘-->ein+Test<--’. Method appendReplacement first appends preceding text ‘+’, then replacement ‘XXX’.

String sb now holds ‘-->XXX+XXX’, while object m is at input position ‘-->ein+Test▵<--’.

Now the purpose of method appendTail becomes clear.

 

StringBuffer appendTail(StringBuffer resultat)

Called after the last desired match, even if stopping early, it appends the input text after that match to the result string in StringBuffer .

In the preceding example,

m.appendTail(sb)

it appends ›<--‹ to sb , producing ›-->XXX+XXX<--‹ and completing search and replace.

 

Search-and-replace examples

These primitives can implement a custom version of replaceAll , as this illustrative example shows:

public static String replaceAll(Matcher m, String ersatztext) {
   m.reset(); // Matcher-Objekt initialisieren.
   StringBuffer resultat = new StringBuffer(); // Darin wird die neue Version aufgebaut.
   while (m.find())
       m.appendReplacement(resultat, ersatztext);
   m.appendTail(resultat);
   return resultat.toString(); // In einen String verwandeln und zurückgeben.
}

Like the real replaceAll method, this ignores the current region (see The Matcher region) and resets it to the whole input first.

Sometimes that is undesirable. This version of replaceAll respects the region; the changed lines are highlighted:

public static String replaceAllRegion(Matcher m, String ersatztext) {
   Integer start = m.regionStart();
   Integer end   = m.regionEnd();
   m.reset().region(start, end); // Matcher initialisieren, aber Region erhalten.
  
   StringBuffer resultat = new StringBuffer(); // Darin wird die neue Version aufgebaut.
   while (m.find())
       m.appendReplacement(resultat, ersatztext);
   m.appendTail(resultat);
   return resultat.toString(); // In einen String verwandeln und zurückgeben.
}

Combining methods reset and region in one statement demonstrates method chaining, explained in Chaining methods.

This slightly more complex fragment converts Celsius temperatures in variable temps to Fahrenheit:

// Matcher aufbauen, der in der Variablen "temps" nach Zahlen, gefolgt von einem "C", sucht.
Matcher m = Pattern.compile("(\\d+(?:\\.(\\d+))?)C\\b").matcher(temps);

StringBuffer resultat = new StringBuffer(); // Darin bauen wir die veränderte Kopie auf.
while (m.find()) {
  float celsius = Float.parseFloat(m.group(1));    // Gefundene Ziffern -> Fließkommazahl.
  int fahrenheit = (int) (celsius * 9/5 + 32);     // In Fahrenheit umrechnen.
  m.appendReplacement(resultat, fahrenheit + "F"); // In das Resultat einfügen.
}
m.appendTail(resultat);
System.out.println(resultat.toString());           // Resultat ausgeben.

If temps contains, for example, ‘von 36.3C bis 40.1C.’, it prints ‘von 97F bis 104F.’.

  

 

 

 

German edition copyright © 2008 by O’Reilly Verlag GmbH & Co. KG
You may print the online version for private use.
Otherwise, this chapter from "Reguläre Ausdrücke" is subject to the same terms as the bound edition: the work and all its parts are protected by copyright. All rights reserved, including reproduction, translation, microfilming, storage and processing in electronic systems.

O’Reilly Verlag GmbH & Co. KG, Balthasarstr. 81, 50670 Köln

back to top