0

I am writing a program which can trace depth of curly braces in a code file line by line, the idea is to have a global variable incremented every-time i find {and decremented every time i find }, this is easy and I already have it done, Now I want to to make sure that I don't count the braces that are inside quotes (i.e. string) or when it's in a comment (// or /* */), I am thinking to utilize the power of regex in this problem, but I am not sure what such regex should look like, I was thinking something like "{ //^"/ "/" " but this is not correct, Any ideas?

James
  • 1,095
  • 7
  • 20
aero
  • 372
  • 1
  • 4
  • 18
  • 1
    Possible duplicate of [Java: Removing comments from string](http://stackoverflow.com/questions/8626866/java-removing-comments-from-string) – Grzegorz Górkiewicz Mar 04 '17 at 21:49
  • 1
    You can do that by using lookahead and lookbehind of regex, e.g. [here](http://www.regular-expressions.info/lookaround.html). And you can use a boolean, when a String is opend by " and reset it when it is closed by ". Then you only count when the boolean is not set. – thopaw Mar 04 '17 at 21:51
  • @ Thomas Pawlitzki , Thanks I'll look into that. – aero Mar 04 '17 at 22:01

1 Answers1

1

You could also try to remove the comments and strings from the lines like this:

lineString.replaceAll("\".*?\"", "")     // strings
          .replaceAll("/\\*.*?\\*/", "") // block comment
          .replaceAll("//.*", "");       // line comment

Afterwards, there should be not comments and strings left. You might be able to put all this in one regex by concatenating it with |.

Edit: I do not know whether block comments in your input span multiple lines. My proposal does not cover that case. As you process the file line by line, you would have to look for /*, set a flag, and ignore everything until you find a */.

Malte Hartwig
  • 4,477
  • 2
  • 14
  • 30