-1

I am trying to find lines with methods definitions in a file. For example, the line is:

// line has TAB indent public Stream<JsonNode> requestDifferences(List<Integer> commitIds) {

The regular expression that I'm trying to use is:

"^.+(!?if|while|for|catch|do|new|return).+\\(.*\\)\\s\\{$"

The example line above matches the regular expression. But all strings that contain anonymous classes, condition, loop and return statements also successfully match the regular expression above.

What is wrong with this expression?

  • If you meant to match a line with no words in your alternation group, you should have written it as `"^(?!.*\\b(?:if|while|for|catch|do|new|return)\\b).+\\(.*\\)\\s*\\{$"` - but it is not a good idea to parse code with a single regex. – Wiktor Stribiżew Nov 20 '17 at 07:55
  • 3
    The regex approach to this is likely to hurt down the road. Consider using a real parser instead: http://javaparser.org/ – Henrik Aasted Sørensen Nov 20 '17 at 07:57
  • 1
    I don't like the idea of parsing code with a single regex either. However, why don't you search for lines starting public/private tag? That will reduce significantly the matches – Cristian Ramon-Cortes Nov 20 '17 at 07:57
  • But what if the line is a class definition or a method has package-private scope (without a keyword)? – Roman Sotnichenko Nov 20 '17 at 08:04
  • And can Javaparser parse a single line? Because I am retrieving differences of a commit from Bitbucket - each of code line is returned in a separate json-array's element. – Roman Sotnichenko Nov 20 '17 at 08:08

1 Answers1

0

(?!if|while|for|catch|do|new|return)^(public\s+|private\s+|protected\s+).+(.)\s{$

try this regex for method line matching. if you don't want match line insert into

(?!if|while|for|catch|do|new|return)

this block.

AJP
  • 43
  • 1
  • 9