QT删除python中的单行注释

python中的#号可能存在于字符串中:

print("'asd#f'00#0" , '#1“23')  #这里才开始注释

没想到用什么正则来删除python中的单行注释

所以解决方案为:

QString removeLineComment(QString sLine)
{
    qDebug() << "removeLineComment:" << sLine;
    QString sRes;
    int nSharpPos = sLine.indexOf('#');
    if (nSharpPos < 0)
        return sLine;
    if (nSharpPos == 0) {
        return "";
    }
    if (sLine.indexOf('\'') < 0 && sLine.indexOf('\"') < 0) {//该行无引号
        sRes = sLine.left(nSharpPos);
        return sRes;
    }

    struct _s_e_ {
        int start;
        int end;
    };
    QList<_s_e_> _list;
    QRegularExpression regex_str("(['\"]{1}).*?\\1");
    auto matches_str = regex_str.globalMatch(sLine);
    if (matches_str.isValid()) {
        while (matches_str.hasNext()) {
            auto m=matches_str.next();
            if (m.hasMatch()) {
                _s_e_ se;
                se.start = m.capturedStart();
                se.end = m.capturedEnd();
                _list << se;                
            }
        }
    }

    sRes = sLine;
    while (nSharpPos>0) {
        bool bInStr = false;
        for (auto se : _list) {
            bInStr = nSharpPos > se.start&&nSharpPos < se.end;
            if (bInStr)
                break;
        }
        if (!bInStr) {
            sRes = sLine.left(nSharpPos);
            break;
        }
        nSharpPos = sLine.indexOf('#', nSharpPos+1);
    }


    return sRes;
}
View Code

 

posted @ 2023-11-05 23:42  吾非无心  阅读(11)  评论(0编辑  收藏  举报