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