QT regularExpressions retrieve numbers

我的梦境 提交于 2019-12-02 06:42:44

问题


I've to split simple QStrings of the form "number number number",for example " 2323 432 1223". The code i use is

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;
}

if the first line being processed is like the example string i get for the first while cycle output:

1= 2323

2= 2323

3=

what is wrong?


回答1:


Your regex only matches 1 or more digits once with re.match. The first two values are Group 0 (the whole match) and Group 1 value (the value captured with a capturing group #1). Since there is no second capturing group in your pattern, match.captured(2) is empty.

You must use QRegularExpressionMatchIterator to get all matches from the current string:

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

Note that (\\d+) contains an unnecessary capturing group, since the whole match can be accessed, too. So, you may use re("\\d+") and then get the whole match with i.next().captured(0).




回答2:


If the usage of regular expressions isn't mandatory, you could also use QString's split()-function.

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


来源:https://stackoverflow.com/questions/46340467/qt-regularexpressions-retrieve-numbers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!