Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which regular expression to find a string not containing a substring?

Tags:

java

regex

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 variable declared like "private static ...", only "private static 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.

like image 470
Med Avatar asked Jul 02 '26 22:07

Med


2 Answers

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

pattern = "private\\s*static(?!\\s*final)";
like image 156
Amber Avatar answered Jul 04 '26 12:07

Amber


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.

like image 25
Stephen C Avatar answered Jul 04 '26 13:07

Stephen C



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!