Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex that Will Match a Java Method Declaration

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.

Here is my regex: "\w+ +\w+ *\(.*\) *\{"

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

int foo()
{

}

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.

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

like image 318
Anton Avatar asked Sep 16 '08 01:09

Anton


People also ask

Which regex does Java use?

Java does not have a built-in Regular Expression class, but we can import the java.util.regex package to work with regular expressions. The package includes the following classes: Pattern Class - Defines a pattern (to be used in a search) Matcher Class - Used to search for the pattern.

What does \\ mean in Java regex?

The backslash \ is an escape character in Java Strings. That means backslash has a predefined meaning in Java. You have to use double backslash \\ to define a single backslash. If you want to define \w , then you must be using \\w in your regex.

How do you match a pattern in regex?

The sequence '\\' matches "\" and "\(" matches "(". Matches any single character. Matches the position at the beginning of the searched string. For example ^CF matches any string starting 'CF'.


2 Answers

(public|protected|private|static|\s) +[\w\<\>\[\]]+\s+(\w+) *\([^\)]*\) *(\{?|[^;])

I think that the above regexp can match almost all possible combinations of Java method declarations, even those including generics and arrays are return arguments, which the regexp provided by the original author did not match.

like image 99
Georgios Gousios Avatar answered Sep 17 '22 13:09

Georgios Gousios


I also needed such a regular expression and came up with this solution:

(?:(?:public|private|protected|static|final|native|synchronized|abstract|transient)+\s+)+[$_\w<>\[\]\s]*\s+[\$_\w]+\([^\)]*\)?\s*\{?[^\}]*\}?

This grammar and Georgios Gousios answer have been useful to build the regex.

EDIT: Considered tharindu_DG's feedback, made groups non-capturing, improved formatting.

like image 45
sbaltes Avatar answered Sep 18 '22 13:09

sbaltes