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