tags:

views:

45

answers:

2

I'd like to create a RegEx Pattern statically, but I think I have the syntax wrong?

static {
  Pattern noHREF = Pattern.compile("<a.+?>", Pattern.CASE_INSENSITIVE);
}

 public static String getStringWithHREFsRemoved(String html) {
    Matcher m = noHREF.matcher(html);
etc.....
+3  A: 

You need to put the noHREF variable as a static member variable of your class.

static Pattern noHREF = Pattern.compile("<a.+?>", Pattern.CASE_INSENSITIVE);

public static String getStringWithHREFsRemoved(String html) {
    Matcher m = noHREF.matcher(html);
    // ...

In the code you wrote in your question, the noHREF variable is imply a local (temporary) variable whose scope is between static { and }.

aioobe
+2  A: 

When you declare

static {
   Pattern noHREF = Pattern.compile("<a.+?>", Pattern.CASE_INSENSITIVE);
}

This is an anonymous static method that is executed when the class is loaded, and the noHREF declaration is a local variable in that method, and not a static field as you are expected. To get a static field, use the declaration

static Pattern noHREF = Pattern.compile("<a.+?>", Pattern.CASE_INSENSITIVE);

This will then allow you to access noHREF from a static method.

mdma
While your information is generally correct, this is a static initializer block, not an anonymous static method. You can similarly create an instance initializer block (omit the `static`, keep the braces). The intended purpose of the initializer blocks is to initialize/instantiate fields of the class, in particular when more than simple assignment is required to achieve the correct values.
Brian S