O'Reilly logo

Java Cookbook by Ian F. Darwin

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Replacing the Matching Text

As we saw in the previous recipe, regular expression patterns involving multipliers can match a lot of input characters with a very few metacharacters. We need a way to replace the text that matched the RE without changing other text before or after it. We could do this manually using the String method substring( ). However, because it’s such a common requirement, the regular expression API provides it for us in methods named subst( ). In all these methods, you pass in the string in which you want the substitution done, as well as the replacement text or “right-hand side” of the substitution. This term is historical; in a text editor’s substitute command, the left-hand side is the pattern and the right-hand side is the replacement text.

// class SubDemo
// Quick demo of substitution: correct "demon" and other 
// spelling variants to the correct, non-satanic "daemon".

// Make an RE pattern to match almost any form (deamon, demon, etc.).
String patt = "d[ae]{1,2}mon";

// A test input.
String input = "Some say Unix hath demons in it!";

// Run it from a RE instance and see that it works
RE r = new RE(patt);
System.out.println(input + " --> " + r.sub(input, "daemon"));

Sure enough, when you run it, it does what it should:

C:\javasrc\RE>java  SubDemo
Some say Unix hath demons in it! --> Some say Unix hath deamons in it!

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required