/** * */ PackageTestjava.java;ImportJava.util.HashMap;ImportJava.util.Map;ImportJava.util.Scanner;ImportJava.util.regex.Matcher;ImportJava.util.regex.Pattern;/** * @authorXXX.SJTU * @function * @date April 12, 2016 *@version */ Public classReplacetest {/** * @paramargs*/ Public Static voidMain (string[] args) {String tempaltecontent= "your" $CarBrand $ "(license plate $carplatenum$) has been leased (order number: $orderNo $). This rental income $rentincome$ yuan, $ServiceExpense $ $ServiceExpenseProxy $ $You 2renteradjust$ $Renter 2youadjust$ $HardwareDeposit $ $OWNERTRANSDEBT $ $TotalIncome $ after 1 business days to settle to the bank card you set up. You can view the details on the app owner Benefits page.; Map Contentparammap=NewHashMap (); Contentparammap.put ("Carbrand", "Audi"); Contentparammap.put ("Carplatenum", "Shanghai A0001"); Contentparammap.put ("OrderNo", "1245221158"); Contentparammap.put ("Rentincome", "2000"); Contentparammap.put ("Serviceexpense", "Platform service charge 100 yuan,"); Scanner SC=NewScanner (tempaltecontent); StringBuffer buf=NewStringBuffer (); Try{Pattern P= Pattern.compile ("[$]" ([^$]*?) [$]"); while(Sc.hasnext ()) {System.out.println (sc.tostring ()); Matcher m=P.matcher (Sc.nextline ()); while(M.find ()) {//Find and Replace parametersSystem.out.println (M.group (1)); //get the value from the map based on keyM.appendreplacement (buf, Contentparammap.get (M.group (1))! =NULL? Contentparammap.get (M.group (1)). ToString (): ""); } m.appendtail (BUF); }//if (Stringutils.isempty (buf.tostring ())) {//buf.append (tempaltecontent);// }}Catch(Exception e) {//logger.error ("Replace SMS template content Error! ", e);E.printstacktrace (); }finally{sc.close (); } System.out.println ("Buf=" +buf); }}
Java Regular expression parsing SMS template