龙盟编程博客 | 无障碍搜索 | 云盘搜索神器
快速搜索
主页 > 软件开发 > JAVA开发 >

关于java.util.regex包中新增字符替换方法的比较

时间:2009-12-23 15:42来源:未知 作者:admin 点击:
分享到:
代码如下: import Java.util.regex.*; public class regex { public regex() { } public static String replaceByRegex (String input,String toChg,String chgTo) { StringBuffer sb = null; if (input==nullinput.length()==0) return input; if (toChg

  代码如下:
  import Java.util.regex.*;
  
  public class regex {
  
   public regex() {
  
   }
  
   public static String replaceByRegex (String input,String toChg,String chgTo) {
  
  StringBuffer sb = null;
  
  if (input==nullinput.length()==0) return input;
  
  if (toChg==nulltoChg.length()==0) return input;
  
  Pattern chagePattern = Pattern.compile(toChg);
  
  Matcher inputMatcher = chagePattern.matcher(input);
  
  sb = new StringBuffer();
  
  while (inputMatcher.find()) {
  
   inputMatcher.appendReplacement(sb,chgTo);
  
  }
  
  inputMatcher.appendTail(sb);
  
  return sb.toString();
  
   }
  
   public static String replaceByStringBuffer(String _old,String _str,String _new)
  
   {
  
  if (_old==null) {return null;}
  
  StringBuffer _temp=new StringBuffer();
  
  int i=0;
  
  int j=0;
  
   while((j=_old.indexOf(_str,0))!=-1)
  
   {
  
  _temp.append(_old.substring(0,j)+_new);
  
  _old=_old.substring(j+_str.length());
  
   }
  
  _temp.append( _old);
  
  return _temp.toString();
  
  }
  
  public static String replaceByString(String _old,String _str,String _new)
  
  {
  
   if (_old==null) {return null;}
  
   String _temp="";
  
   int i=0;
  
   int j=0;
  
  while((j=_old.indexOf(_str,0))!=-1)
  
  {
  
   _temp+=_old.substring(0,j)+_new;
  
   _old=_old.substring(j+_str.length());
  
  }
  
   _temp+=_old;
  
   return _temp;
  
   }
  
   public static void main(String[] args) throws Throwable {
  
  String tmp = "the the ii bb ttisc hisadf. oeoflaksdjflkjeivnlaskdfjiieiah";
  
  long t = System.currentTimeMillis();
  
  for (int i=0;i<100000;i++,regex.replaceByStringBuffer(tmp,"i","WW"));
  
  System.out.println("replace it by string buffer :"+(System.currentTimeMillis()-t));
  
  t = System.currentTimeMillis();
  
  for (int i=0;i<100000;i++,regex.replaceByString(tmp,"i","WW"));
  
  System.out.println("replace it by string :"+(System.currentTimeMillis()-t));
  
  t = System.currentTimeMillis();
  
  for (int i=0;i<100000;i++,regex.replaceByRegex(tmp,"i","WW"));
  
  System.out.println("replace it by regex :"+(System.currentTimeMillis()-t));
  
   }
  
  }
  
  测试结果:
  replace it by string buffer :2443
  
  replace it by string :3305
  
  replace it by regex :4226
  
  可见,
  
精彩图集

赞助商链接