开发者

Understanding Pattern and Matcher

开发者 https://www.devze.com 2022-12-13 22:40 出处:网络
Consider this code: import java.util.regex.*; public class Pattern3 { /** * @param args the command line arguments

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?


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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消