在使用正则表达式时,利用好其预编译功能,可以有效加快正则匹配速度。

同时,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()) {
...
}
}
正则的预编译主要注意两点:

1.  Pattern 表达式要提前定义,不要再需要的地方临时定义;

2. Pattern 表达式要定义为 static final 静态变量,以避免执行多次预编译。

相关文章:

  • 2022-12-23
  • 2021-08-17
  • 2022-12-23
  • 2021-11-22
  • 2022-12-23
  • 2021-11-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-10-26
  • 2021-12-30
  • 2022-12-23
  • 2021-12-24
  • 2022-12-23
  • 2022-02-22
  • 2021-10-06
相关资源
相似解决方案