Reputation: 24316
Regular expressions are a weakness of mine.
I am looking for a regex or other technique that will allow me to read an arbitrary string and determine if it is a valid java function.
Good:
public void foo()
void foo()
static protected List foo()
static List foo()
Bad:
public List myList = new List()
Code:
For String line : lines.
{
If(line.matches("(public|protected|private)*(/w)*(")
}
Is there such a regex that will return true if it's a valid java function?
Upvotes: 3
Views: 2628
Reputation: 6800
/^\s*(public|private|protected)?\s+(static)?\s+\w+\s+\w+\s*\(.*?\)\s*$/m
Matches:
This is FAR from complete, but ought to suit your needs.
Upvotes: 6
Reputation: 18168
Depends how rigorous you need it to be, because it can get fairly complex as a regex.
The grammar for method declarations in Java is something like the following:
method_declaration
::=
{ modifier } type identifier
"(" [ parameter_list ] ")" { "[" "]" }
( statement_block | ";" )
and you have to check things like having multiple modifiers but not the same modifier repeated or multiple scope modifiers, also other things like the type and identifier isn't one of the Java keywords. Starts getting hairy... I doubt you'd want to write your own Java parser.
Upvotes: 3