[英]Regex in python for not matching word
I am reviewing java code and there are so many classes to check, I made a regex to find a method written in java that doesn't close IO stream within finally block. 我正在审查java代码并且有很多类要检查,我做了一个正则表达式来找到一个用java编写的方法,它不会在finally块中关闭IO流。
(?s)(?<=public|private|protected).
(?<!finally).*?.close\\(\\)\\;
For some reason this doesn't work and it matches even those methods that has finally block, so below is found too 由于某种原因,这不起作用,它甚至匹配最终阻塞的那些方法,所以下面也找到了
public testMethod(){
InputStream stream = .....
try{
//do something
} finally {
if(stream != null){
stream.close();
}
}
}
While only below should be matched 虽然只有下面应该匹配
public testMethod(){
InputStream stream = .....
//do something
if(stream != null){
stream.close();
}
}
Any pointers ? 有什么指针吗?
Your regex should probably be : (?s)(?<=public|private|protected)((?!finally).)*close\\(\\)\\;
你的正则表达式应该是:( (?s)(?<=public|private|protected)((?!finally).)*close\\(\\)\\;
. 。 Demo on regex101 . 在regex101上演示。
Explanation : ((?!finally).)*
verify that the rest of the string does not contain finally
. 说明 : ((?!finally).)*
验证字符串的其余部分不包含finally
。
Note : in order to cover all cases, you might also want to check if the close()
is actually inside the block of the finally. 注意 :为了涵盖所有情况,您可能还想检查close()
是否实际位于finally块中。 You can do it with an expression like (?s)(?<=public|private|protected)((?!finally[^}]*close\\(\\)\\;).)*close\\(\\)\\;
您可以使用类似(?s)(?<=public|private|protected)((?!finally[^}]*close\\(\\)\\;).)*close\\(\\)\\;
. 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.