Julian
Julian

Reputation: 325

Regular Expression For Detecting Recursive Java Functions

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.

Upvotes: 0

Views: 106

Answers (3)

PM 77-1
PM 77-1

Reputation: 13334

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?

Upvotes: 3

Andrey Chaschev
Andrey Chaschev

Reputation: 16476

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());

Upvotes: 0

Mike Strobel
Mike Strobel

Reputation: 25623

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.

Upvotes: 1

Related Questions