Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

regex

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?

like image 507
Woot4Moo Avatar asked Jan 24 '26 20:01

Woot4Moo


1 Answers

/^\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.

like image 160
FrankieTheKneeMan Avatar answered Jan 26 '26 11:01

FrankieTheKneeMan