title: Java - regex pattern compilation best practice (with enum)
body: <p>I'm trying to create an enum which holds the regex string, while making sure that the pattern only compiles once because <a href="https://stackoverflow.com/questions/4935216/shouldnt-static-patterns-always-be-static">pattern compilation is expensive</a> and I do reuse the same pattern a lot. I'm trying to achieve a dynamically compiled Pattern object depending of the type of enum selected. However, I'm stuck at the following. Can anyone kindly provide some guidance, or suggest a better way of achieving this? </p>
  
  <pre><code>public enum LOG_SCANNER{
      FOO_STRING(".*XXXX$"),
      BAR_STRING(".*YYYY.*"),
      ;
  
      static Pattern p;
      static {
          p = Pattern.compile(regex); // Compilation failes here
  
      }
  
  
      String regex;
      private LOG_NAME_MATCHER(String regex) {
          this.regex = regex;
      }
  
  
  }
  </code></pre>
  
  <p>edit:
  Please note that i'm not using regex to search for something that could be achieved with String.endsWith() or .contains(). ( ".*XXXX$" ) is simply an example.</p>