熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> Java編程 >> JSP教程 >> 正文

關於java.util.regex 包中新增字符替換方法的比較

2013-11-15 11:34:44  來源: JSP教程 

  代碼如下:
  import javautilregex*;
  
  public class regex {
  
   public regex() {
  
   }
  
   public static String replaceByRegex (String inputString toChgString chgTo) {
  
    StringBuffer sb = null;
  
    if (input==null||inputlength()==) return input;
  
    if (toChg==null||toChglength()==) return input;
  
    Pattern chagePattern = pile(toChg);
  
    Matcher inputMatcher = chagePatternmatcher(input);
  
    sb = new StringBuffer();
  
    while (inputMatcherfind()) {
  
     inputMatcherappendReplacement(sbchgTo);
  
    }
  
    inputMatcherappendTail(sb);
  
    return sbtoString();
  
   }
  
   public static String replaceByStringBuffer(String _oldString _strString _new)
  
   {
  
    if (_old==null) {return null;}
  
    StringBuffer _temp=new StringBuffer();
  
    int i=;
  
    int j=;
  
     while((j=_oldindexOf(_str))!=)
  
     {
  
      _tempappend(_oldsubstring(j)+_new);
  
      _old=_oldsubstring(j+_strlength());
  
     }
  
    _tempappend( _old);
  
    return _temptoString();
  
    }
  
    public static String replaceByString(String _oldString _strString _new)
  
    {
  
     if (_old==null) {return null;}
  
     String _temp=;
  
     int i=;
  
     int j=;
  
      while((j=_oldindexOf(_str))!=)
  
      {
  
       _temp+=_oldsubstring(j)+_new;
  
       _old=_oldsubstring(j+_strlength());
  
      }
  
     _temp+=_old;
  
     return _temp;
  
   }
  
   public static void main(String[] args) throws Throwable {
  
    String tmp = the the ii bb ttisc hisadf oeoflaksdjflkjeivnlaskdfjiieiah;
  
    long t = SystemcurrentTimeMillis();
  
    for (int i=;i<;i++regexreplaceByStringBuffer(tmpiWW));
  
    Systemoutprintln(replace it by string buffer :+(SystemcurrentTimeMillis()t));
  
    t = SystemcurrentTimeMillis();
  
    for (int i=;i<;i++regexreplaceByString(tmpiWW));
  
    Systemoutprintln(replace it by string :+(SystemcurrentTimeMillis()t));
  
    t = SystemcurrentTimeMillis();
  
    for (int i=;i<;i++regexreplaceByRegex(tmpiWW));
  
    Systemoutprintln(replace it by regex :+(SystemcurrentTimeMillis()t));
  
   }
  
  }
  
  測試結果:
  replace it by string buffer :
  
  replace it by string :
  
  replace it by regex :
  
  可見在 String比較大的情況下替換性能差異將更大
  
  其中subString 也會降低處理的性能在可能的情況下可以使用charAt這裡只是做個測試
  
  不過在一般數據量不大以及使用頻率不高的情況下regex有著更強大的功能
From:http://tw.wingwit.com/Article/program/Java/JSP/201311/19241.html
  • 上一篇文章:

  • 下一篇文章:
  • 推薦文章
    Copyright © 2005-2013 電腦知識網 Computer Knowledge   All rights reserved.