0
\$\begingroup\$

I am trying to identify a java function block addition in a diff file (new line start with + in diff). For that I am using regular expression.

It is working fine, however I need to identify all (if not, at least maximum) possible combinations of keyword used in java method declarations.

Here is my regular expression written in my java program

Pattern functionPatter = Pattern.compile("\\+\\s*(public|private|protected)?(\\s+static)?(\\s+final)?\\s+\\w+\\s+\\w+\\s*\\(.*?\\)\\s*(throws .*)+\\{.*\\}",Pattern.DOTALL); 

Please suggest me if I am missing anything.

\$\endgroup\$

2 Answers 2

2
\$\begingroup\$

I have no idea what you are trying to match with \\s+\\w+\\s+\\w+\\s*. If you are looking for a return type, then that won't do at all.

It appears that you are trying to match the function body using \\{.*\\}. That won't work, because braces may be nested, and regular expressions cannot handle nesting.

Modifier keywords can appear in any order, and you are missing a few, such as:

  • synchronized
  • transient
  • volatile
  • strictfp

If you want to implement this correctly, don't just make assumptions based on code that you have been seeing. Read the Java Language Specification.

\$\endgroup\$
1
\$\begingroup\$

For the java spec there are already complete parsers based e.g. on JavaCC or Antlr. IMHO the safest way would be process a java file using one of those and extracting the methods from there. Processing using regular expressions is quite difficult, e.g. how about methods in comments.

https://github.com/antlr/grammars-v4/tree/master/java8

\$\endgroup\$
1
  • \$\begingroup\$ or methods as String value String m = "public static void main()"; \$\endgroup\$ Commented Sep 25, 2017 at 7:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.