1

我正在解析一个包含以下数据包的文件:

[propertyID="123000"] { 
  fillColor : #f3f1ed;
  minSize : 5;
  lineWidth : 3;
}

要扫描这个[propertyID="123000"]片段,我有这个 QRegExp

QRegExp("^\b\[propertyID=\"c+\"\]\b");

但这不起作用?这里我有示例代码来解析上面的文件:

QRegExp propertyIDExp= QRegExp("\\[propertyID=\".*\"]");
propertyIDExp.setMinimal(true);

QFile inputFile(fileName);
if (inputFile.open(QIODevice::ReadOnly))
{
    QTextStream in(&inputFile);
    while (!in.atEnd())
    {
        QString line = in.readLine();

        // if does not catch if line is for instance
        // [propertyID="123000"] {
        if( line.contains(propertyIDExp) )
        {
            //.. further processing
        }
    }
    inputFile.close();
}
4

2 回答 2

0
QRegExp("\\[propertyID=\".+?\"\\]")

您可以使用.它.会匹配除newline.以外的任何字符+?"

于 2015-08-19T11:53:25.323 回答
0

使用以下表达式:

QRegExp("\\[propertyID=\"\\d+\"]");

正则表达式演示

在 Qt 正则表达式中,您需要使用双反斜杠转义正则表达式特殊字符,并且要匹配数字,您可以使用速记类\d。此外,\b单词边界阻止了您的正则表达式匹配,因为它无法在字符串 start 和[between]和空格之间匹配(或\B改为使用)。

要匹配引号之间的任何内容,请使用否定字符类:

QRegExp("\\[propertyID=\"[^\"]*\"]");

查看另一个演示

作为替代方案,您可以在.*and的帮助下使用惰性点匹配QRegExp::setMinimal()

QRegExp rx("\\[propertyID=\".*\"]");
rx.setMinimal(true);

在 Qt 中,.匹配任何字符,包括换行符,因此请小心使用此选项。

于 2015-08-19T11:46:54.213 回答