Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to find static (non final) variables

I am trying to do a search in my Eclipse (Java) workspace to find all instances of static variables that are not final.

I tried various regexes but they do not result in any matches. Can someone suggest a regex that will match all lines containing static and not containing final, and not ending in a {?

The last part about not ending with a { will eliminate static methods.

An example:

public class FlagOffendingStatics {
  private static String shouldBeFlagged = "not ok";
  private static final String ok = "this is fine";
  public static void methodsAreOK() {

  }
}
like image 692
user31837 Avatar asked Oct 27 '08 17:10

user31837


2 Answers

This pattern works:

[^(final)] static [^(final)][^(\})]*$

Here is a test:

$ cat test.txt
private int x = "3";
private static x = "3";
private final static String x = "3";
private static final String x = "3";
private static String x = "3";
public static void main(String args[]) {
        blah;
}

$ grep "[^(final)] static [^(final)][^(\})]*$" test.txt
private static x = "3";
private static String x = "3";

(I realize that private static x = "3"; isn't valid syntax, but the pattern still holds ok.)

The pattern accounts for the fact that final can appear before or after static with [^(final)] static [^(final)]. The rest of the pattern, [^(\})]*$, is meant to prevent any { characters from appearing in the remainder of the line.

This pattern will not work however if anyone likes to write their method statements like this:

private static void blah()
{
     //hi!
}
like image 185
matt b Avatar answered Oct 23 '22 06:10

matt b


Instead of checking for the absence of a brace, I would look for a semicolon at the end:

^(?![ \t]*import\b)(?!.*\bfinal\b).*\bstatic\b.*;[ \t]*$
like image 4
Alan Moore Avatar answered Oct 23 '22 05:10

Alan Moore