Alternate actions in regular expressions and reset () methods
Import Java.util.regex.Matcher; Import Java.util.regex.Pattern; /** * @author Clydelou * */public class Regexreplacement {/** * @param args/public static void Main (string[) args) { TODO auto-generated method stub String str = "Zju University in Zhejiang Province, china/n I love you!!!"; str = Str.replaceall ("(? m) ^ +", "");//delete all spaces at the beginning of each line, (? m) to open multiline state, so that each row achieves this effect, rather than just deleting the space at the beginning of the text. System.out.println (str); str = Str.replaceall ("{2,}", ""), or where there will be two or more than two spaces, reduced to a single space. System.out.println (str); Pattern p = pattern.compile ("[Aeiou]"); Matcher m = p.matcher (str); StringBuffer sbuf = new StringBuffer (); while (M.find ()) {m.appendreplacement (Sbuf, M.group (). toUpperCase ()); M.appendtail (sbuf);//Copy remaining unhandled parts to Sbuf// Implements a terminal append-and-replace step. This method reads characters from the input sequence, starting at the//append position, and appends them to the given String buffer. It is//intended to being invoked after one or more invocations of the The//Appendreplacement to copy the remainder of the input//sequence. System.out.println (Sbuf.tostring ()); The reset () method to apply an existing Matcher object to a new character sequence M=pattern.compile ("[FRB][AIU][GX]"). Matcher ("Fix the Rug with bags"); while (M.find ()) System.out.print (M.group () + "/t"); System.out.println (); M.reset ("Fix the Rig with rags"); while (M.find ()) System.out.print (M.group () + "/t"); System.out.println (); } }
Run Result:
Zju University in Zhejiang Province,
I Love You!!!
Zju University in Zhejiang Province,
I Love You!!!
Zju UnIvErsIty in Zhejiang Province,
I Love You!!!
Fix Rug Bag
Fix Rig Rag