java regular expressions: performance and alternative

后端 未结 2 775
时光说笑
时光说笑 2020-12-13 00:20

Recently I have been had to search a number of string values to see which one matches a certain pattern. Neither the number of string values nor the pattern itself is clear

2条回答
  •  爱一瞬间的悲伤
    2020-12-13 00:51

    Regular expressions in Java are compiled into an internal data structure. This compilation is the time-consuming process. Each time you invoke the method String.matches(String regex), the specified regular expression is compiled again.

    So you should compile your regular expression only once and reuse it:

    Pattern pattern = Pattern.compile(regexPattern);
    for(String value : values) {
        Matcher matcher = pattern.matcher(value);
        if (matcher.matches()) {
            // your code here
        }
    }
    

提交回复
热议问题