3

We are developing an eclipse plugin tool to remove sysout statements from the workspace projects. We are able to achieve our goal only partially. If the sysouts are in one line we are able to delete it easily. But if the sysout is spanned over a couple of lines (generally occurs due to code formatting), this is when we face the issue.

For Example :

System.out.println("Hello World");

The regular expression to remove this line would be simple:

System.out.println*

But if the code is this:

System.out.println(New Line)("HelloWorld");

This is where the issue comes. Can anyone please suggest how I can replace this using a java regular expression.

nhahtdh
  • 52,949
  • 15
  • 113
  • 149
saikris
  • 101
  • 1
  • 6
  • 2
    If you're building an Eclipse plugin you have access to the Java AST, so why even use a regular expression? – jkovacs May 17 '13 at 10:24
  • You cannot do this with a regular expression, because you would need to find the corresponding closing bracket (or correct semicolon, but that wouldn't be much easier). You could check the answer to this question for an alternative approach http://stackoverflow.com/questions/546433/regular-expression-to-match-outer-brackets – Vincent van der Weele May 17 '13 at 10:24
  • Note that 'System.out.println*' is not correct regexp for this case since '.' is any character. – Bitman May 17 '13 at 10:36
  • As @user2758929 noted you should have a closer look at existing APIs, mainly JDT, but there also exists [MoDisco](http://eclipse.org/MoDisco/) for example – SpaceTrucker May 17 '13 at 11:57

1 Answers1

0

I suggest

String regex = "System\.out\.println[^)]+[)]\s*;"

Where the [^)]+ will scan until the closing parenthesis. However, this will fail in multiple cases:

  • (possibly-unbalanced) parenthesis inside the output
  • commented-out code
  • the few cases where it is possible to omit the ';'
  • cases where System.out is assigned to another variable, instead of being used directly

Go the extra mile and use a Eclipse's in-built parser (which understands lexical issues, comments, and can flag any compile-time references to System.out).

Community
  • 1
  • 1
tucuxi
  • 15,614
  • 2
  • 36
  • 70
  • Thanks for the response. As told by you, the regex works fine albeit with a few shortcomings. I was trying to find out how I can handle this scenario using the AST Parser. I am going through the API. It would really help if you can share any sample code that would search the instance of a string pattern in the compilation unit using this API. Thanks – saikris May 20 '13 at 06:09