zoukankan      html  css  js  c++  java
  • 正则表达式预编译功能的正确使用

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

    同时,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 静态变量,以避免执行多次预编译。

  • 相关阅读:
    第四章 Zookeeper技术内幕
    容器--TreeMap
    算法--红黑树实现介绍(二)
    算法---红黑树实现介绍(一)
    容器--WeakHashMap
    基础-WeakReference
    容器--IdentityHashMap
    容器--EnumMap
    容器--HashMap
    容器--Map和AbstractMap
  • 原文地址:https://www.cnblogs.com/zhouj850/p/12867468.html
Copyright © 2011-2022 走看看