Woot4Moo
Woot4Moo

Reputation: 24316

regular expression to match the format of any legal java function declaration

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

Answers (2)

FrankieTheKneeMan
FrankieTheKneeMan

Reputation: 6800

/^\s*(public|private|protected)?\s+(static)?\s+\w+\s+\w+\s*\(.*?\)\s*$/m

Matches:

  • Start of line <^>
  • Arbitrary White space <\s*>
  • Optional scope <(public|private|protected)?>
  • At least one space <\s+>
  • Optional keyword static <(static)?>
  • At least one space <\s+>
  • A java identifier (which you should hope is a class name or literal) <\w+>
  • At least one space <\s+>
  • A java identifier (the function name) <\w+>
  • Open paren <(>
  • arbitrary arguments (no checking done here, because of the massive mess) <.*?>
    • The does lazy matching
  • Close paren <)>
  • arbitrary whitespace <\s*>
  • End of line

This is FAR from complete, but ought to suit your needs.

Upvotes: 6

dule
dule

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:

Java method declaration BNF:

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

Related Questions