3

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 ?

2
  • A method in Java can just start without (public|private|protected) also Commented Jun 22, 2016 at 5:10
  • Thanks for replying, but lets assume our coders used access modifiers for all methods. Commented Jun 22, 2016 at 5:13

1 Answer 1

1

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\(\)\;.

Sign up to request clarification or add additional context in comments.

2 Comments

Works perfect thanks, about close inside finally block, how can I achieve this ?
@Dwarf_Ostrich No problem. However you should avoid to use comment for this purpose

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.