知识大全 关于java.util.regex 包中新增字符替换方法的比较
Posted 字符
篇首语:人格成熟的重要标志:宽容、忍让、和善。本文由小常识网(cha138.com)小编为大家整理,主要介绍了知识大全 关于java.util.regex 包中新增字符替换方法的比较相关的知识,希望对你有一定的参考价值。
代码如下: 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()== ) return input; if (toChg==null||toChg length()== ) return input; Pattern chagePattern = pile(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= ; int j= ; while((j=_old indexOf(_str ))!= ) _temp append(_old substring( 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= ; int j= ; while((j=_old indexOf(_str ))!= ) _temp+=_old substring( 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= ;i< ;i++ regex replaceByStringBuffer(tmp i WW )); System out println( replace it by string buffer : +(System currentTimeMillis() t)); t = System currentTimeMillis(); for (int i= ;i< ;i++ regex replaceByString(tmp i WW )); System out println( replace it by string : +(System currentTimeMillis() t)); t = System currentTimeMillis(); for (int i= ;i< ;i++ regex replaceByRegex(tmp i WW )); System out println( replace it by regex : +(System currentTimeMillis() t)); 测试结果: replace it by string buffer : replace it by string : replace it by regex : 可见 在 String比较大的情况下替换性能差异将更大 其中subString 也会降低处理的性能 在可能的情况下可以使用charAt 这里只是做个测试 不过在一般数据量不大 以及使用频率不高的情况下regex有着更强大的功能 cha138/Article/program/Java/JSP/201311/19241相关参考