QT regularExpressions retrieve numbers

前端 未结 2 1768
旧时难觅i
旧时难觅i 2021-01-25 01:15

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(\"(\\         


        
相关标签:
2条回答
  • 2021-01-25 01:53

    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);
    }
    
    0 讨论(0)
  • 2021-01-25 02:01

    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).

    0 讨论(0)
提交回复
热议问题