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

王朝java/jsp·作者佚名  2008-05-31
宽屏版  字体: |||超大  

代码如下:

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

可见,

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
© 2005- 王朝网络 版权所有