O'Reilly logo

Java™ Phrasebook by Timothy Fisher

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 Matched Text

String pattern = "[TJ]im";
											Pattern regPat = Pattern.compile(pattern);
											String text = "This is jim and Tim.";
											Matcher matcher = regPat.matcher(text);
											String string2 = matcher.replaceAll("John");

In this phrase, we replace text that is matched against our pattern sting with alternate text. The value of string2 at the end of this phrase will be the string

This is jim and John.

The occurrence of "jim" will not be replaced because the regular expression matching is case sensitive by default. See the previous phrase for non-case sensitive matching. As in basic matching shown in the previous phrase, we use the Pattern, and Matcher classes in the same way. The new step here is our call to the Matcher’s replaceAll() method. We pass ...

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