Skip to Main Content
Java Cookbook
book

Java Cookbook

by Ian F. Darwin
June 2001
Intermediate to advanced content levelIntermediate to advanced
888 pages
21h 1m
English
O'Reilly Media, Inc.
Content preview from Java Cookbook

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!
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Practical Cloud-Native Java Development with MicroProfile

Practical Cloud-Native Java Development with MicroProfile

Emily Jiang, Andrew McCright, John Alcorn, David Chan, Alasdair Nottingham
Distributed Computing in Java 9

Distributed Computing in Java 9

Raja Malleswara Rao Malleswara Rao Pattamsetti

Publisher Resources

ISBN: 0596001703Supplemental ContentCatalog PageErrata