Shouldn't “static” patterns always be static?

前端 未结 5 1528
名媛妹妹
名媛妹妹 2021-01-01 10:42

I just found a bug in some code I didn\'t write and I\'m a bit surprised:

Pattern pattern = Pattern.compile(\"\\\\d{1,2}.\\\\d{1,2}.\\\\d{4}\");
Matcher matc         


        
5条回答
  •  一整个雨季
    2021-01-01 11:11

    first, the bug in pattern is because dot (.) matches everything. If you want to match dot (.) you have to escape it in regex:

    Pattern pattern = Pattern.compile("\\d{1,2}\\.\\d{1,2}\\.\\d{4}");

    Second, Pattern.compile() is a heavy method. It is always recommended to initialize static pattern (I mean patterns that are not being changed or not generated on the fly) only once. One of the popular ways to achieve this is to put the Pattern.compile() into static initializer.

    You can use other approach. For example using singleton pattern or using framework that creates singleton objects (like Spring).

提交回复
热议问题