... until the collector arrives ...

This "blog" is really just a scratchpad of mine. There is not much of general interest here. Most of the content is scribbled down "live" as I discover things I want to remember. I rarely go back to correct mistakes in older entries. You have been warned :)

2007-04-30

Grepping for static fields in Java

Here is a regular expression (Java-syntax) that will match all static non-final fields in Java source code (to a reasonable approximation):

\sstatic(?![^=]*\sfinal\s)(?![^=]*\()(?![^=]*\sclass\s)(?![^=]*\senum\s)\s

In summary, if finds all lines that contain the word static, but not followed by  final, class, enum, or an open parenthesis (signifying a method) prior to an equals sign.  This pattern will return false positives such as when static appears after an equals sign or final precedes static.  It will also miss cases that are split over multiple lines.  Both circumstances are unusual to the point of rarity and a more elaborate pattern to find such cases will run considerably slower.

For some reason this expression works erratically within Eclipse.  Eclipse seems to occasionally search across line boundaries -- but only sometimes?!  To correct his behaviour, use this pattern instead (changes in bold):

\sstatic(?![^=\n]*\sfinal\s)(?![^=\n]*\()(?![^=\n]*\sclass\s)(?![^=\n]*\senum\s)\s

Blog Archive