将匹配 Java 方法声明的正则表达式 [英] Regex that Will Match a Java Method Declaration

查看:14
本文介绍了将匹配 Java 方法声明的正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个与 java 方法声明匹配的正则表达式.我想出了一个匹配方法声明的方法,但它要求方法的左括号与声明在同一行.如果您对改进我的正则表达式有任何建议或只是有更好的建议,请提交答案.

I need a Regex that will match a java method declaration. I have come up with one that will match a method declaration, but it requires the opening bracket of the method to be on the same line as the declaration. If you have any suggestions to improve my regex or simply have a better one then please submit an answer.

这是我的正则表达式:"w+ +w+ *(.*) *{"

对于那些不知道 java 方法是什么样子的人,我将提供一个基本的方法:

For those who do not know what a java method looks like I'll provide a basic one:

int foo()
{

}

Java 方法还可以添加几个可选部分,但这些是方法保证具有的唯一部分.

There are several optional parts to java methods that may be added as well but those are the only parts that a method is guaranteed to have.

更新:我当前的正则表达式是 "w+ +w+ *([^)]*) *{" 以防止出现 Mike 和 adkom 描述的情况.

Update: My current Regex is "w+ +w+ *([^)]*) *{" so as to prevent the situation that Mike and adkom described.

推荐答案

您是否考虑过匹配实际可能的关键字?例如:

Have you considered matching the actual possible keywords? such as:

(?:(?:public)|(?:private)|(?:static)|(?:protected)s+)*

它可能更有可能正确匹配,但它也可能使正则表达式更难阅读......

It might be a bit more likely to match correctly, though it might also make the regex harder to read...

这篇关于将匹配 Java 方法声明的正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆