代码如下:
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有着更强大的功能,
闽公网安备 35060202000074号