正則表示式預編譯應用
阿新 • • 發佈:2018-12-26
使用正則表示式的預編譯功能,可以有效加快正則匹配速度。
Pattern要定義為static final靜態變數,以避免執行多次預編譯。
示例:
【錯誤用法】
// 沒有使用預編譯 private void func(...) { if (Pattern.matches(regexRule, content)) { ... } } // 多次預編譯 private void func(...) { Pattern pattern = Pattern.compile(regexRule); Matcher m = pattern.matcher(content); if (m.matches()) { ... } }
【正確用法】
private static final Pattern pattern = Pattern.compile(regexRule);
private void func(...) {
Matcher m = pattern.matcher(content);
if (m.matches()) {
...
}
}
原文連結:https://blog.csdn.net/qq_35312171/article/details/82663344