Python正则表达式提取Java方法的参数类型

要求:对于一个java方法的代码片段,给定其方法名称,提取该方法的参数类型。

测试用例1:

methodName = 'createUserInfoPrompt'
codeContent = """
    public UserInfo createUserInfoPrompt(@NotNull SSHAuthConfiguration configuration, @NotNull Session session) {
        return new UIPrompter(configuration, session);
    }
"""

期望输出

['Configuration', 'Session']

测试用例2:

methodName = 'propertyNameToMethodName'
codeContent = """
/**
 * Converts a user's property name to a bean method name.
 *
 * @param propertyName the user property name
 * @return the equivalent bean method name
 */
public static String propertyNameToMethodName(String propertyName) {
    char ch = propertyName.charAt(0);
    if (Character.isLowerCase(ch))
        propertyName = Character.toUpperCase(ch) + propertyName.substring(1);
    return propertyName;
}
"""

期望输出

['String']

python代码

def getParameterTypesFromCode(methodName:str, codeContent:str):
    # 定义方法名称和参数类型的正则表达式
    method_pattern = r'\b' + methodName + r'\s*\(\s*([^)]*)\s*\)'

    # 匹配 Java 代码中的指定方法
    match = re.search(method_pattern, codeContent)
    # 输出匹配结果
    if match:
        parameter_types = re.findall(r'@?\w+(?:\[\])?(?=\s+\w+)', match.group())
        # 过滤所有注解,如@NotNull
        parameter_types = [type_str for type_str in parameter_types if not type_str.startswith('@')]
        return parameter_types
    else:
        return ['notfound']

对于mathod_pattern,解释如下:

method_pattern = r'\b' + methodName + r'\s*\(\s*([^)]*)\s*\)'
  • \b 匹配单词边界,用来确保方法名的前面是一个单词分界符(例如空格或符号)。

  • methodName 要匹配的方法名,由函数的参数传入。

  • \s* 匹配零个或多个空格,用来匹配方法名和左括号之间的空格。

  • (\s*匹配左括号,方法名和参数列表的开始。

  • ([^)]*) 匹配方法参数列表,即方法名和左括号之间的内容。这里使用了一个字符类 [^)] 来匹配除了右括号之外的所有字符, 表示匹配零个或多个字符。这个括号内的内容会作为一个捕获组,可以用来提取参数列表中的参数类型。

  • \s*\) 匹配右括号,表示参数列表结束。同样使用了 \s* 来匹配右括号和参数列表之间可能存在的空格。

使用 r 前缀可以让 Python 把反斜杠 \ 当做普通字符处理,避免转义符号被解释。

对于下面这段代码,解释如下:

parameter_types = re.findall(r'@?\w+(?:\[\])?(?=\s+\w+)', match.group())

re.findall() 函数使用正则表达式在给定字符串中查找匹配的所有子串,并将所有匹配项作为列表返回。在这里,我们使用下面这个正则表达式来匹配参数类型。

@?\w+(?:\[\])?(?=\s+\w+) 
  • @? 匹配一个可选的 @ 字符。

  • \w+ 匹配一个或多个字母、数字或下划线字符。

  • (?:\[\])? 匹配一个可选的空的方括号,这个子表达式被放在一个非捕获组 (?:) 中,表示匹配但不捕获。

  • (?=\s+\w+) 使用一个正向前瞻断言,表示必须跟着至少一个空格和一个单词字符,但这部分不会被匹配。这个断言保证我们只匹配参数类型而不是变量名。

因此, 它可以匹配参数类型,并且过滤掉了变量名称以及注解。

部分代码由ChatGPT生成,对两个关键语句的中文解释由ChatGPT生成

猜你喜欢

转载自blog.csdn.net/qq_42276781/article/details/129097758