How to match a method block using regex?

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

Take an example.

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

I write a regex, \"\\\\

7条回答
  •  萌比男神i
    2021-01-06 10:36

    You need to enable DOTALL mode. Then dot will match newLine chars. Just include (?s) in the beginning of your regex.

     String s = "   public static FieldsConfig getFieldsConfig(){\n"
                 + "   if(xxx) {\n"
                 + "              sssss;\n"
                 + "   }\n"
                 + "      return;\n"
                 +"}";
     Matcher m = Pattern.compile("(?s)\\s*public\\s+static\\s+\\w+?\\sgetFieldsConfig\\(\\s*\\).*").matcher(s);
     m.find();
     System.out.println(m.group());
    

    Outpup is all method body as you wanted. Without (?s) it matches only the first line. But you cannot parse java code with regex. Others already said that. This regex will match everything from beginning of method signature to the end of file. How do you match it only until the end of method body is reached? Method can contain many {....} as well as many return;. Regex is not a magic stick.

提交回复
热议问题