High performance simple Java regular expressions

前端 未结 4 529
北海茫月
北海茫月 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:25

    If you want to avoid creating a new Matcher for each Pattern, use the usePattern() method, like so:

    Pattern[] pats = {
      Pattern.compile("123"),
      Pattern.compile("abc"),
      Pattern.compile("foo")
    };
    String s = "123 abc";
    Matcher m = Pattern.compile("dummy").matcher(s);
    for (Pattern p : pats)
    {
      System.out.printf("%s : %b%n", p.pattern(), m.reset().usePattern(p).find());
    }
    

    see the demo on Ideone

    You have to use matcher's reset() method too, or find() will only search from the point where the previous match ended (assuming the match was successful).

提交回复
热议问题