0

I am wondering what would be a regular expression that would detect any function declaration which has a body containing a call to itself in Java.

Example of a method that would match:

public int method()

{*n

method();

}*n

Thank you for any help.

3
  • 3
    Is there any particular reason why you want to do this with a regex? Commented Nov 26, 2013 at 23:43
  • 3
    To do this accurately you must parse the Java code. Regexes are not powerful enough to parse Java code. Consider method overloading... how would match argument types to pick the correct method being invoked? What if the method contained a String literal that contained a { or } character? Just some simple counterexamples that would break any regex-based approach. Commented Nov 26, 2013 at 23:46
  • 1
    To do this type of static analysis, you're better off using a tool like ASM Commented Nov 26, 2013 at 23:50

3 Answers 3

3

Consider the following code samples:

public int method() {

System.out.prontln("method() started");
}

or

public int method() {

// this method() is just an example

}

Do you see now that you need a full-blown parser?

Sign up to request clarification or add additional context in comments.

1 Comment

@Julian - Please acknowledge that you got my point, so I can delete this non-answer.
1

I don't see how this could be done reliably with a regular expression, since the arguments to any method call could be arbitrarily complex, and even include anyonymous classes containing similarly named methods.

So, the answer is "no"; at least not if you want it to be reliable.

Comments

0

This is a quick and dirty example. It would lead to many false positives and generally be slow. It doesn't take into account curly brackets and strings which could contain curlies. However, it works for your input. :-)

Matcher m = Pattern.compile("([\\w\\d_$]+\\s*\\([^)]*\\))[^{]*\\{.*\\1[^}]+}", Pattern.DOTALL |Pattern.MULTILINE).matcher(s1);

System.out.println(m.matches());

Comments

Your Answer

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.