tags:

views:

82

answers:

5

Hi everyone,

I am working on a simple tool to check Java coding guidelines on a project. One of those guidelines is to verify that there is no variables declared like "private static ...", only "private statitc final ..." is allowed.

I am wondering how I can get this result. I wrote this one : pattern = "private\\s*static\\s*(?!final)";

But it is not working. How can I get only the entries without the "final" keyword ?

Thanks, Med.

+3  A: 

That should work, yes. You might want to move the second whitespace inside the lookahead:

pattern = "private\\s*static(?!\\s*final)";
Amber
Ok thanks! Indeed, it is working better when I move the spaces inside the lookahead.
Med
A: 

using \s+ to require the space made it start working for me.

private\\s+static\\s+(?!final).+

I also added the .+ to match the rest of the line which might not be what you're after.

Andrew
+2  A: 

I think that you are going about this problem the wrong way. Writing a half-decent style checker is a difficult task, especially if you are going to cope with all of the possible "trivial" variations of constructs (e.g. different modifier orders) and all points of potential fragility (e.g. "hits" on stuff in comments and string literals).

IMO, a better approach would be to use an existing source code checker and define your own style checking rules. This is easy to do in PMD. PMD has the advantage that its rules operate on a parsed AST. This makes them much less sensitive to syntactic variations, etc than anything implemented using regex matches on source files.

Stephen C
A: 

I agree with Andrew's answer (regardless of whether this is the right way to solve this problem). You should definitely be using \\s+ instead of \\s* to check for the existence of spaces since those spaces have to exist. Your regex would match privatestaticfoobar, which is obviously not what you want.

Dean Hall
A: 

You can't really do this accurately with a regular expression. Programming languages require parsers, not regular expressions. It's a basic theorem.

EJP