How to match a method block using regex?

前端 未结 7 1245
孤街浪徒
孤街浪徒 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:38

    Thank all of you. After some consideration, I work out a reliable way to some degree in my situation. Now share it.

    String regex ="\\s*public\s+static\s+[\w\.\<\>,\s]+\s+getFieldsConfig\\(.*?\\)\\s*\\{.*?\\}(?=\\s*(public|private|protected|static))";
    
    String regex2 = "\\s*public\s+static\s+[\w\.\<\>,\s]+\s+getFieldsConfig\\(.*?\\)\\s*\\{.*?\\}(?=(\\s*}\\s*$))";
    
    regex = "(" + regex +")|("+ regex2 + "){1}?";
    
    Pattern pattern = Pattern.compile(regex, Pattern.DOTALL)
    

    It can match my method body well.

    PS Yes, the regex maybe not the suitable way to parse a method very strictly. Generally speaking, regex is less effort than programming and work right in specific situation. Adjust it and Sure it works for you.

    0 讨论(0)
提交回复
热议问题