我正在编写一个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注释始终是可选的,可以省略
TL; DR:Regexp对于您的用例来说不够强大
任何正则表达式都相当于Deterministic finite automaton。
Regexp并不总是适合解析代码。它有时需要有一个regexp不提供的Pushdown automaton。您可能想要查看ANTLR,它是完整的特征语言解析器。
有关类似示例,请参阅此question。
Here是一些github repo,旨在使用ANTLR解析java。