简体   繁体   中英

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.

(?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\\(\\)\\; . Demo on regex101 .

Explanation : ((?!finally).)* verify that the rest of the string does not contain 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. You can do it with an expression like (?s)(?<=public|private|protected)((?!finally[^}]*close\\(\\)\\;).)*close\\(\\)\\; .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM