【问题标题】:RegExp to find command line argumentsRegExp 查找命令行参数
【发布时间】:2013-10-14 14:55:33
【问题描述】:

我正在开发一个终端程序以在远程机器上执行应用程序。 您可以像在 windows cmd.exe 中一样传递命令:

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

为了使这成为可能,我必须处理带引号的文本并从该字符串中解析命令及其参数。 在记事本++中,我找到了一个正则表达式来修补它们(([^" \t\n]+)|("[^"]*"))+,它可以工作。在Qt4.8.1 我试过了:

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

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

我该怎么做才能让它工作?

解决方案:(感谢 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;
}

【问题讨论】:

    标签: c++ regex qt qt4 qregexp


    【解决方案1】:

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

    (你只是过度使用了反向引用)

    确保您正在捕获所有结果。

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

    【讨论】:

    • 感谢您的快速回复。还必须更改一些 qt 代码才能“找到”正确的匹配项。很棒的链接顺便说一句,有助于理解很多(作为一个血腥的正则表达式初学者我可以使用它);)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-25
    • 2011-02-25
    • 2013-02-14
    相关资源
    最近更新 更多