How to match a method block using regex?

Viewed 4963

Take an example.

 public static FieldsConfig getFieldsConfig(){
    if(xxx) {
      sssss;
    }
   return;
}

I write a regex, "\\s*public\\s*static.*getFieldsConfig\\(.*\\)\\s*\\{"

It can match only the first line. But how to match right to the last "}" of the method?

Help me. Thanks.

Edit: The content of method {} is not specified. But pattern is surely like this,

  public static xxx theKnownMethodName(xxxx) {
    xxxxxxx
  }
7 Answers

I had to modify this answer for my own needs. I wanted capture groups for the entire method as well as the names of each method in the file. I only need these two capture groups. This requires the single line (s) flag in PCRE. The global (g) flag would be needed to in other REGEX parses to capture the full file and not just one match. I nested the bracket capture @SamWhan showed to allow five levels of nesting. This should get the job done as more is against most recommended standards. This makes this REGEX really expensive so be warned.

(?:public|private|protected|static|final|abstract|synchronized|volatile)\s*(?:(?:(?:\w*\s)?(\w+))|)\(.*?\)\s*(?:\{(?:\{[^{}]*(?:\{[^{}]*(?:\{[^{}]*(?:\{[^{}]*(?:\{[^{}]*(?:\{[^{}]*}|.)*?[^{}]*}|.)*?[^{}]*}|.)*?[^{}]*}|.)*?[^{}]*}|.)*?[^{}]*}|.)*?})
Related