使用正則表達式的預編譯功能,可以有效加快正則匹配速度。
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()) {
...
}
}
點贊 5
————————————————
版權聲明:本文爲CSDN博主「misthee」的原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/qq_35312171/article/details/82663344