正则表达式qt中的条件

condition in regular expression qt

本文关键字:条件 qt 正则表达式      更新时间:2023-10-16

我写了一个正则表达式来查找范围('{'|'}')。我想找到没有评论的范围,但我不明白我在哪里犯了错误。下面是一段代码:

    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;
   }

例如,我们有一些文本:

//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;
}

首先,用正则表达式正确解析c++代码通常是不可能的。想想嵌套注释、行延续、包含"//""/*"等的字符串!

其次,通常很难让正则表达式匹配某些内容。

但是您的特定示例可以用像这样的正则表达式解析:^(?!(//|/*))*{:

    end  = text.indexOf(QRegExp("^(?!(//|/\*))*\{"),start);
    end2  = text.indexOf(QRegExp("^(?!(//|/\*))*\}"), start);