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.