如何使用正则表达式匹配方法块? [英] How to match a method block using regex?

查看:29
本文介绍了如何使用正则表达式匹配方法块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

举个例子.

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

我写了一个正则表达式,"\\ s * public \\ s * static.* getFieldsConfig \\(.* \\)\\ s * \\ {"

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?

帮帮我.谢谢.

未指定方法{}的内容.但是模式肯定是这样的,

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

  public static xxx theKnownMethodName(xxxx) {
    xxxxxxx
  }

推荐答案

谢谢大家.经过深思熟虑,我在某种程度上找到了一种可靠的方法.现在分享.

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 是的,正则表达式可能不是严格严格解析方法的合适方法.一般来说,正则表达式比在特定情况下正确编程和工作要少.调整它并确保它对您有用.

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.

这篇关于如何使用正则表达式匹配方法块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆