天天看點

替換字元串小工具,支援大小寫是否區分

 /**

  * 替換字元串

  * @param iscase 是否區分大小寫

  * @param source 源字元串

  * @param oldstring 待替換舊字元串

  * @param newstring 新字元串

  * @return 替換後的字元串

  */

 public static string replacestring(boolean iscase,string source, string oldstring,string newstring){

  string ret="";

  if (!iscase) //不區分大小寫

  {

   matcher m = pattern.compile(oldstring, pattern.case_insensitive).matcher(source);

   ret=m.replaceall(newstring);

   //system.out.println("使用正規表達式不區分大小寫的替換結果"+ret);

  }

  else // 區分大小寫

   matcher m = pattern.compile(oldstring, pattern.canon_eq).matcher(source);

   //system.out.println("使用正規表達式區分大小寫的替換結果"+ret);

  return ret;

  }

測試:

 string b="<img src=\"http://www.aaa.com/\">";

  b+="<img src=\"http://www.bbb.com/\">";

  b+="<img src=\"http://www.ccc.com/\">";

  b+="<img src=\"http://www.ddd.com/\">";

  string v=replacestring(false,b,"http://","//");

  system.out.println("v="+v);

  string w=replacestring(true,b,"http://","//");

  system.out.println("w="+w);