服务热线:13616026886

技术文档 欢迎使用技术文档,我们为你提供从新手到专业开发者的所有资源,你也可以通过它日益精进

位置:首页 > 技术文档 > JAVA > 新手入门 > 基础入门 > 查看文档

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


  代码如下:
  import java.util.regex.*;
  
  public class regex {
  
   public regex() {
  
   }
  
   public static string replacebyregex (string input,string tochg,string chgto) {
  
    stringbuffer sb = null;
  
    if (input==null||input.length()==0) return input;
  
    if (tochg==null||tochg.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
  
  可见,在 string比较大的情况下替换性能差异将更大.
  
  其中substring 也会降低处理的性能,在可能的情况下可以使用charat,这里只是做个测试
  
  不过在一般数据量不大,以及使用频率不高的情况下regex有着更强大的功能,

扫描关注微信公众号