0

I wrote a regular expression for find the scopes('{'|'}'). I want to find the scopes that wasn't commented, but I don't understand where I have mistake. Here are a fragment of code:

    while (start >= 0 && end >=0) {
        start = text.indexOf("\n", start);
        end  = text.indexOf(QRegExp("^.*[{](?!=[//]|[/*]|[*]))"),start);
        end2  = text.indexOf(QRegExp("^.*[}](?!=[//]|[/*]|[*]))"), start);
        if (end < end2) {
            text.replace(end,"\n{\n");
        }
        else  text.replace(end2,"\n}\n");
        ++start;
   }

For example, we have some text:

//dfsdkfj ksjdfksjdf {  <- this symbol should be skipped
public SystemBlock()
{  //<- this symbol should be found. 
    this.producer = "none";
    this.motherBoard = "none";
    this.processor = "none";
    this.ram = "none";
    this.gpu = "none";
    this.price = 0;
    this.eventSupport = null;
}
Mat
  • 202,337
  • 40
  • 393
  • 406
Max
  • 101

1 Answers1

0

First of all, it is generally impossible to correctly parse C++ code with regular expressions. Think about nested comments, line continuations, strings containing "//", "/*" etc.!

Secondly, it is generally hard to have a regex not match something. See this question for more details.

But your specific example can be parsed with a regex like this: ^(?!(//|/\*))*{ :

    end  = text.indexOf(QRegExp("^(?!(//|/\\*))*\\{"),start);
    end2  = text.indexOf(QRegExp("^(?!(//|/\\*))*\\}"), start);
Community
  • 1
  • 1
rustyx
  • 80,671
  • 25
  • 200
  • 267