【问题标题】:Java Regular Expression to match only method name in signatureJava正则表达式仅匹配签名中的方法名称
【发布时间】:2021-06-18 06:41:10
【问题描述】:

我有一个代表方法签名的字符串列表。例如:

public String someMethod(String parameter)

public static void someAnotherMethod(double doubleParam, List<String> stringList)

通过使用以下正则表达式(链接https://regex101.com/r/TwRRbp/1),我可以获得方法名称和参数:

\w+\(.*\)

最后,我得到以下信息:

someMethod(String parameter)

someAnotherMethod(double doubleParam, List<String> stringList)

但我只需要方法名。我想我需要关注左括号。

【问题讨论】:

标签: java regex text-processing


【解决方案1】:

你说的很对。使用正向 Lookahead,您可以匹配后跟左括号的任何单词字符。如果你想真正确定,你可以搜索单词,后跟括号和大括号:

(\w+)(?=\(.*\)\s*\{)

【讨论】:

    【解决方案2】:

    使用

    [a-zA-Z0-9_]+(?=\()
    

    proof

    解释

    --------------------------------------------------------------------------------
      [a-zA-Z0-9_]+            any character of: 'a' to 'z', 'A' to 'Z',
                               '0' to '9', '_' (1 or more times (matching
                               the most amount possible))
    --------------------------------------------------------------------------------
      (?=                      look ahead to see if there is:
    --------------------------------------------------------------------------------
        \(                       '('
    --------------------------------------------------------------------------------
      )                        end of look-ahead
    

    【讨论】:

      猜你喜欢
      • 2011-03-01
      • 1970-01-01
      • 2020-02-18
      • 1970-01-01
      • 1970-01-01
      • 2016-01-22
      • 1970-01-01
      • 2011-11-03
      • 1970-01-01
      相关资源
      最近更新 更多