Java 正则表达式仅匹配签名中的方法名称
Java Regular Expression to match only method name in signature
我有一个表示方法签名的字符串列表。例如:
public String someMethod(String parameter)
public static void someAnotherMethod(double doubleParam, List<String> stringList)
通过使用下面的正则表达式(link https://regex101.com/r/TwRRbp/1),我可以得到方法名和参数:
\w+\(.*\)
最后,我得到以下信息:
someMethod(String parameter)
someAnotherMethod(double doubleParam, List<String> stringList)
但我只需要方法名。我想我需要关注左括号。
你说的很对。使用正先行,您可以匹配任何后跟左括号的单词字符。如果你真的想确定,你可以搜索单词,然后是括号和大括号:
(\w+)(?=\(.*\)\s*\{)
使用
[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
我有一个表示方法签名的字符串列表。例如:
public String someMethod(String parameter)
public static void someAnotherMethod(double doubleParam, List<String> stringList)
通过使用下面的正则表达式(link https://regex101.com/r/TwRRbp/1),我可以得到方法名和参数:
\w+\(.*\)
最后,我得到以下信息:
someMethod(String parameter)
someAnotherMethod(double doubleParam, List<String> stringList)
但我只需要方法名。我想我需要关注左括号。
你说的很对。使用正先行,您可以匹配任何后跟左括号的单词字符。如果你真的想确定,你可以搜索单词,然后是括号和大括号:
(\w+)(?=\(.*\)\s*\{)
使用
[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