科技行者

行者学院 转型私董会 科技行者专题报道 网红大战科技行者

知识库

知识库 安全导航

至顶网软件频道关于java.util.regex 包中新增字符替换方法的比较

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

  • 扫一扫
    分享文章到微信

  • 扫一扫
    关注官方公众号
    至顶头条

  代码如下:   import java.util.regex.*;      public class regex {       public regex() {       }       public static String repla

作者:中国IT实验室 来源:中国IT实验室 2007年9月25日

关键字: 编程 java

  • 评论
  • 分享微博
  • 分享邮件

  代码如下:
  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有着更强大的功能,

查看本文来源

    • 评论
    • 分享微博
    • 分享邮件