The difference between the matches ()/lookingat ()/find () methods and the use of replaceall () replacefirst () appendreplacement () appendtail (), please refer to the code
Package test; import Java. util. regEx. matcher; import Java. util. regEx. pattern; public class regtest {public static void main (string [] ARGs) {pattern Reg = pattern. compile ("(20 \ D {2})-([01] \ D)-([0-3] \ D)"); matcher = NULL; system. out. println (Reg. pattern (); matcher = reg. matcher (""); // The matches () method attempts to show matching of the entire target character and returns the true value if (matcher. matches () {system. out. println ("time:" + matcher. group (0); system. out. println ("year:" + matcher. group (1); system. out. println ("year:" + matcher. group (2); system. out. println ("year:" + matcher. group (3);} pattern reg2 = pattern. compile ("\ D *"); system. out. println (reg2.pattern (); matcher = reg2.matcher ("2012 ABCD"); // The lookingat () method checks whether the target string starts with a matched substring if (matcher. lookingat () {system. out. println ("Num:" + matcher. group ();} pattern reg3 = pattern. compile ("\ D +"); system. out. println (reg3.pattern (); matcher = reg3.matcher ("asf2012abcd2011jdf2010jk"); // find () method attempts to find the next matched substring in the target string while (matcher. find () {system. out. println ("matcherstr:" + matcher. group ();} // appendreplacement () replaces the current matched substring with the specified string, add the substring after replacement and the string segment after the matched substring to a stringbuffer object, pattern reg4 = pattern. compile ("(Hello | goodbye)"); matcher = reg4.matcher ("sayhelloandsaygoodbyeandsayhelloandsaysomething"); stringbuffer sb = new stringbuffer (); While (matcher. find () {system. out. println ("matcherstr:" + matcher. group (); matcher. appendreplacement (SB, "it"); system. out. println ("SB:" + Sb);} // appendtail () the method adds the remaining strings after the last matching operation to a stringbuffer object. // you can call the appendreplacement method once or multiple times to copy the remaining input sequence matcher. appendtail (SB); system. out. println ("SB:" + Sb );}}
The output result is as follows:
(20\d{2})-([01]\d)-([0-3]\d)time:2012-02-25year:2012year:02year:25\d*num:2012\d+matcherStr:2012matcherStr:2011matcherStr:2010matcherStr:hellosb:sayITmatcherStr:goodbyesb:sayITandsayITmatcherStr:hellosb:sayITandsayITandsayITsb:sayITandsayITandsayITandsaysomething