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 the text we want to use as replacement text as a parameter. This text will then replace all occurrences of the matched pattern. This is a powerful tool for replacing portions of a string with an alternate string.

Another useful method of replacing text is through the use of the appendReplacement() and appendTail() methods of the Matcher class. Using these methods together allows you to replace occurances of a substring within a string. The code below shows an example of this technique:

Pattern p = Pattern.compile("My"); Matcher m = p.matcher("My dad and My mom"); StringBuffer sb = new StringBuffer(); boolean found = m.find(); while(found) {    m.appendReplacement(sb, "Our");    found = m.find(); } m.appendTail(sb); System.out.println(sb);


The output of this code is the following line printed from the System.out.println() method:

Our dad and Our mom


In this code, we create a Pattern object to match the text "My". The appendReplacement() method writes characters from the input sequence ("My dad and my mom") to the string buffer sb, up to the last character preceding the previous match. It then appends the replacement string, passed as the second parameter, to the string buffer. Finally, it sets the current string position to be at the end of the last match. This repeats as long as matches are found. When no more matches are found, the appendTail() method is used to append the remaining portion of the input sequence to the string buffer.




JavaT Phrasebook. Essential Code and Commands
Java Phrasebook
ISBN: 0672329077
EAN: 2147483647
Year: 2004
Pages: 166

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net