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.

200_success
145k22 gold badges190 silver badges478 bronze badges
asked Sep 25, 2017 at 5:02
\$\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.

answered Sep 25, 2017 at 6:20
\$\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

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

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.