I'm trying to create an enum which holds the regex string, while making sure that the pattern only compiles once because pattern compilation is expensive 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?
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;
}
}
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.