如何用regex提取java方法参数

2024-06-09 08:45:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个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 {

请求参数始终是第一个不是用@ApiParam或@QueryParam注释的参数。在这种情况下,我的目标是portfoliosugestionrequestportfoliosugestionrequest。注释@Valid和@NotNull总是可选的,可以省略


Tags: the方法脚本信息which参数valuejava
1条回答
网友
1楼 · 发布于 2024-06-09 08:45:10

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

任何regexp都等价于Deterministic finite automaton。你知道吗

regexp并不总是适合解析代码。它有时需要一个regexp没有提供的Pushdown automaton。您可能需要研究ANTLR这是一个完整的功能语言解析器。你知道吗

参见question了解类似的示例。你知道吗

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

相关问题 更多 >