How to match a method block using regex?

前端 未结 7 1314
孤街浪徒
孤街浪徒 2021-01-06 10:06

Take an example.

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

I write a regex, \"\\\\

7条回答
  •  臣服心动
    2021-01-06 10:35

    I decided to take it one step further ;)

    Here's a regex that'll give you the modifiers, type, name and body of a function in different capture groups:

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

    It handles nested braces (@callOfCode it is (semi-)possible with regex ;) and a fixed set of modifiers.

    It doesn't handle complicated stuff like braces inside comments and stuff like that, but it'll work for the simplest ones.

    Regards

    Regex101 sample here

    Edit: And to answer your question ;), what you're interested in is capture group 4.

    Edit 2: As I said - simple ones. But you could make it more complicated to handle more complicated methods. Here's an updated handling one more level of nesting.

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

    And you could another level... and another... But as someone commented - this shouldn't be done by regex. This however handles simple methods.

提交回复
热议问题