QString解析系统变量

时间:2013-08-27 09:34:21

标签: c++ regex windows qt environment-variables

我应该如何解析包含系统变量的QString?我想要的是什么:

QString path = "%WINDIR%\\System32\\";
QString output  = parse(path);
QDebug()<<output; \\ output is "C:\\Windows\\System32\\"

2 个答案:

答案 0 :(得分:2)

我想你想要这样的东西:

// Untested
QString parse(QString str)
{
    int pos = 0;
    QRegExp rx("%([^%]+)%"); // Match env var between two '%'
    rx.setMinimal(true);
    while((pos = rx.indexIn(str, pos)) != -1)
    {
        // Replace env var
        QString capture = rx.cap(1);
        QString replacement = getenv(capture.toAscii());
        str.replace("%" + capture + "%", replacement);

        // Skip env var + two '%'
        pos += rx.matchedLength() + 2;
    }
    return str;
}

QString path = parse("%WINDIR%\\System32");

答案 1 :(得分:0)

我想,这就是你要找的东西。请试试这个

QString windir = getenv ("WINDIR"); // Expanded
if (windir.isEmpty()) {
    fprintf(stderr, "Generator requires WINDIRto be set\n");

}    
windir += "\\System32";
qDebug()<<windir;