regexqtqt4qregexp

qregexp extract all numbers from string


I'm quite noob with regular expression, all i want to do is to get all numbers from a string.

QRegExp rx;
rx.setPattern("\\d+");
rx.indexIn("this string contains number 123 and 567*872");
QStringList MyList = rx.capturedTexts();

Expected result is: 123 and 567 and 872. What i get is: 123


Solution

  • You need to get all matches with a loop like

    QRegExp rx("\\d+");
    QString str = ""this string contains number 123 and 567*872"";
    QStringList MyList;
    int pos = 0;
    
    while ((pos = rx.indexIn(str, pos)) != -1) {
        MyList << rx.cap(0);
        pos += rx.matchedLength();
    }
    

    Here, rx.cap(0) accesses Group 0, the whole match. The QRegExp::indexIn attempts to find a match in str from position offset (0 by default). If offset is -1, the search starts at the last character; if -2, at the next to last character; etc. While the position is not -1, we may iterate through all the matches in the string.