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

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

Search and replace can be implemented with the methods already discussed, but the Matcher object provides more convenient methods:

 

String replaceAll(String ersatztext)

Returns a string in which every piece matched by the regex is replaced with the ersatztext , processed according to the rules below (see The replacement text).

The method resets the current region to the entire subject string by calling reset internally, so it ignores region limits. Search-and-replace examples describe a version of replaceAll that respects region boundaries.

This method is also accessible through the replaceAll method of the String class:

string.replaceAll(regex, ersatztext);

is equivalent to:

Pattern.compile(regex).matcher(String).replaceAll(ersatztext)

 

String replaceFirst(String ersatztext)

This method works much like replaceAll, but replaces only the first match with the ersatztext .

It too has a counterpart through the method replaceFirst for Strings, analogous to replaceAll.

 

static String quoteReplacement(String text)

Since Java 1.5, quoteReplacement is a static method returning a string intended as ersatztext for the above methods. It escapes characters that could otherwise matter when replacement text is processed as described below, where a usage example also appears for quoteReplacement.

 

Examples of simple search and replace

This simple example replaces every “Java 1.5” with “Java 5.0”, translating engineering terminology into marketing language:

String text = "Vor Java 1.5 war Java 1.4.2. Nach Java 1.5 kommt Java 1.6.";
String regex = "\\bJava\\s*1\\.5\\b";
Matcher m = Pattern.compile(regex).matcher(text);
String result = m.replaceAll("Java 5.0");
System.out.println(result);

This gives:

Vor Java 5.0 war Java 1.4.2. Nach Java 5.0 kommt Java 1.6.

If the Pattern and Matcher objects are not needed afterward, chain everything into one line:

Pattern.compile("\\bJava\\s*1\\.5\\b").matcher(text).replaceAll("Java 5.0")

(If the regex is reused in the same thread, saving the compiled Pattern object is worthwhile; see The Pattern.compile factory method).

The same operation can replace “Java 1.6” with “Java 6.0” too, requiring only a small regex change and a corresponding replacement-text change discussed next.

Pattern.compile("\\bJava\\s*1\\.([56])\\b").matcher(text).replaceAll("Java $1.0")

With the same text as before, this gives:

Vor Java 5.0 war Java 1.4.2. Nach Java 5.0 kommt Java 6.0.

All these examples could use replaceFirst instead of replaceAll , replacing only the first match. This may be desired or simply more efficient when only one match is possible, known from external information about the data or from the regex’s construction.

 

The replacement text

The replacement text argument to replaceAll and replaceFirst, as well as the method appendReplacement in the next section, is processed specially for each match before replacing it:

  • Every ›$1‹, ›$2‹, and so on in the replacement is replaced with the text captured by the corresponding group in the latest match. ($0 denotes the entire match.)

    If ›$‹ is followed by anything other than an ASCII digit, IllegalArgumentException is thrown.

    After ›$‹, only meaningful group numbers are allowed. If the regex has three groups, for example, ›$25‹ in the replacement is interpreted as $2 followed by ›5‹. A ›$6‹ causes this regex to throw IndexOutOfBoundsException .

  • A backslash escapes the following character, so a literal dollar in replacement text is written ›\$‹. Similarly, a backslash requires ›\\‹. In a string literal these backslashes must themselves be doubled, requiring four consecutive backslashes for one in the replacement, "\\\\". If the regex has twelve groups and only group 1 followed by ›2‹ is wanted, use ›$1\2‹.

For replacement text with unknown contents, use Matcher.quoteReplacement to neutralize any metacharacters. If uRegex contains a regex and uRepl the unknown replacement text, this ensures the match is replaced with exactly that text:

Pattern.compile(uRegex).matcher(text).replaceAll(Matcher.quoteReplacement(uRepl))

  

 

 

 

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