开发者

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

开发者 https://www.devze.com 2023-01-09 00:38 出处:网络
I am working on a simple tool to check Java coding guideli开发者_高级运维nes on a project. One of those guidelines is to verify that there is no variable declared like \"private static ...\", only \"p

I am working on a simple tool to check Java coding guideli开发者_高级运维nes 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.


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

pattern = "private\\s*static(?!\\s*final)";


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.


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.


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消