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

查看:76
本文介绍了将匹配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 + * \(。* \)* \ {

Here is my regex: "\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天全站免登陆