The creator of static instances of Java?

I would like to create a RegEx template statically, but I think my syntax is wrong?

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

 public static String getStringWithHREFsRemoved(String html) {
    Matcher m = noHREF.matcher(html);
etc.....
+3
source share
2 answers

You need to put the variable noHREFas 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 that you wrote in your question, the noHREF variable means a local (temporary) variable whose scope is between static {and }.

+3
source

When you announce

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

, , noHREF - , , . ,

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

noHREF .

+2

Source: https://habr.com/ru/post/1759548/


All Articles