views:

169

answers:

3

Consider this code:

import java.util.regex.*;

public class Pattern3 {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here

        Pattern p = Pattern.compile("Our"); //line 1
        Matcher m = p.matcher("Our mom and Our dad"); //line 2

        //p.compile(mom); commented line

         StringBuffer s = new StringBuffer();



       boolean found = m.find();

        while (found){
            m.appendReplacement(s, "My"); //line 3
            found=m.find();
        }

       m.appendTail(s); //line 4
       System.out.println(s);
    }

}

a)Why do I need to call m.appendTrail(s) on line 4 to get the unchopped string?

b) Why doesn't the output change when I uncomment and place "mom" as the new regex expression?

+3  A: 

Just read the documentation for

Matcher.appendReplacement and

Matcher.appendTail

It's all explained there what is the intention on using these two methods together.


Changing the pattern after having created an instance of a matcher of course won't influence the already created matcher. You have to change the pattern before you create the matcher.

jitter
+1  A: 

Answer to b)

Pattern.compile() is a static method. If you uncomment p.compile();, it will create a new object that you discard (it isn't assigned to anything). To get what you intended, you would need to do something like:

p = Pattern.compile("mom");

and then get a new matcher from the newly created pattern.

Craig Putnam
A: 

Answer to a)

.appendReplacement() iterates along the Matcher String ("Our mom and Our dad") and, if the pattern ("Our") is found, it substitutes the replacement String ("My") for the pattern ("Our") and puts whatever it iterated over into the StringBuffer (s). If no more patterns are found, it does nothing. That is, it won't append anything after the last pattern. Therefore, .appendTail() is called to get the remainder of the Matcher String.

m.replaceAll("My"); can be used to achieve the same result.

John Kinzie