QT regularExpressions检索数字

时间:2017-09-21 09:37:16

标签: qt qregularexpression

我要拆分表格"号码编号"的简单QS字符串,例如" 2323 432 1223"。 我使用的代码是

QString line;
QRegularExpression re("(\\d+)");
QRegularExpressionMatch match;

while(!qtextstream.atEnd()){
     line = qtextstream.readLine();
     match = re.match(line);
     std::cout<<"1= "<<match.captured(0).toUtf8().constData()<<std::endl;
     std::cout<<"2= "<<match.captured(1).toUtf8().constData()<<std::endl;
     std::cout<<"3= "<<match.captured(2).toUtf8().constData()<<std::endl;
}

如果正在处理的第一行就像我得到的示例字符串 对于第一个while循环输出:

1 = 2323

2 = 2323

3 =

出了什么问题?

2 个答案:

答案 0 :(得分:2)

您的正则表达式仅匹配一个或多个数字一次re.match。前两个值是组0(整个匹配)和组1值(值捕获与捕获组#1)。由于模式中没有第二个捕获组,match.captured(2)为空。

您必须使用QRegularExpressionMatchIterator从当前字符串中获取所有匹配项:

QRegularExpressionMatchIterator i = re.globalMatch(line);
while (i.hasNext()) {
    qDebug() << i.next().captured(1); // or i.next().captured(0) to see the whole match
}

请注意(\\d+)包含不必要的捕获组,因为也可以访问整个匹配。因此,您可以使用re("\\d+"),然后使用i.next().captured(0)获得整个匹配。

答案 1 :(得分:0)

如果正则表达式的使用不是强制性的,您也可以使用QString&#39; split()-function

QString str("2323 432 1223");
QStringList list = str.split(" ");
for(int i = 0; i < list.length(); i++){
    qDebug() << list.at(i);
}