High performance simple Java regular expressions

前端 未结 4 604
北海茫月
北海茫月 2021-02-08 03:44

Part of the code I\'m working on uses a bunch of regular expressions to search for some simple string patterns (e.g., patterns like \"foo[0-9]{3,4} bar\"). Currently, we use sta

4条回答
  •  刺人心
    刺人心 (楼主)
    2021-02-08 04:32

    If you expect less than 50% of lines matching your regex, you can first try to test for some subsequence via String.indexOf() which is about 3 to 20 times faster for simple sequence compared to regex matcher:

    if (line.indexOf("foo")>-1) && pattern.matcher(line).matches()) {
        ...
    

    If you add to your code such heuristics, remember to always well document them, and verify using profiler that code is indeed faster compared to simple code.

提交回复
热议问题