如何使用正则表达式提取java方法参数

问题描述 投票:1回答:1

我正在编写一个Python脚本来解析后端服务中的Java类,以便提取必要的信息。我需要的一件事是从java方法中提取请求参数。

public\s+[\w<>\[\]]+\s+(\w+)\s*\(([^{]+)(^(@ApiParam(.*)\))|^(@PathParam(.*))|^(@QueryParam(.*))|(@\w+\s+)?)((\w+)\s+(\w+))

到目前为止我得到的...它已经在括号()中给了我方法参数但是我不能过滤掉@ApiParam和@QueryParam注释。

/*Some annotations*/
public PortfolioSuggestion calculatePortfolioSuggestion(
        @ApiParam(required = true,
                  value = "Request containing the answers which were answered by the user and an\n" +
                          "investment for which suggestion should be calculated")
        @Valid @NotNull PortfolioSuggestionRequest portfolioSuggestionRequest,
        @ApiParam(value = "The optional product key")
        @QueryParam("product") ProductType productType)
        throws SuggestionsCalculationException {

request参数始终是第一个未使用@ApiParam或@QueryParam注释的参数。在这种情况下,我的目标是PortfolioSuggestionRequest和portfolioSuggestionRequest。 @Valid和@NotNull注释始终是可选的,可以省略

java python regex python-3.x
1个回答
3
投票

TL; DR:Regexp对于您的用例来说不够强大

任何正则表达式都相当于Deterministic finite automaton

Regexp并不总是适合解析代码。它有时需要有一个regexp不提供的Pushdown automaton。您可能想要查看ANTLR,它是完整的特征语言解析器。

有关类似示例,请参阅此question

Here是一些github repo,旨在使用ANTLR解析java。

© www.soinside.com 2019 - 2024. All rights reserved.