RegEx查找命令行参数

时间:2013-10-14 14:55:34

标签: c++ regex qt qt4 qregexp

我正在使用终端程序在远程计算机上执行应用程序。 您可以像在Windows cmd.exe中一样传递命令,如:

"C:\random Directory\datApplication.py" "validate" -r /c "C:\anotherDirectory"

为了使这成为可能,我必须处理引用的文本并从该字符串解析命令及其参数。 在notepad ++中我找到了一个RegExp来修补它们(([^" \t\n]+)|("[^"]*"))+并且它有效。在Qt4.8.1我尝试过:

static const QRegExp re("(([^\" \\t\\n]+)|(\"[^\"]*\"))+");
re.matchExact(str); // str is something like shown above
qDebug() << re.capturedTexts();

这段代码只打印了"C:\random Directory\datApplication.py"的3倍,仅此而已。 它应该打印出作为单个对象输入的每个参数......

我能做些什么让它发挥作用?

解决方案:(感谢Lindrian)

const QString testText = "\"C:\\random Directory\\datApplication.py\" \"validate\" -r /c \"C:\\anotherDirectory\"";
static const QRegExp re("([^\" \\t\\n]+|\"[^\"]*\")+");
int pos = 0;
while ((pos = re.indexIn(testText)) != -1) //-i indicates that nothing is found
{
    const int len = re.matchedLength();
    qDebug() << testText.mid(pos,len);
    pos += len;
}

1 个答案:

答案 0 :(得分:3)

FTFY:([^" \t\n]+|"[^"]*")

(你刚刚过度使用backrefs)

确保您捕获所有结果。

演示:http://regex101.com/r/pR8oF5