[SOLVED]Weird regex behavior...



  • Hi guys,

    I have some problem with regex in Qt. I wrote a small program to match all consecutive numbers in a given string, but the program fails to work correctly.

    Here is the code:
    @#include <QtGui>
    #include <iostream>

    int main() {
    QRegExp rx("[0-9]+");
    QString str = "35.625(+2.125)";
    int pos = 0;

     while ((pos = rx.indexIn(str, pos)) != -1) {
          std::cout << rx.cap(1).toStdString() << " ";
          pos += rx.matchedLength();
     }
     
     std::cout << std::endl;
     return 0;
    

    }
    @

    And the output is... an empty line?????



  • Well... In fact I want to match all numbers; I added some redundant parenthesis, and "(([0-9]*)\.?([0-9]+))" works perfectly for me.

    Why? According to the doc --
    bq. For historical reasons, quantifiers (e.g. ) that apply to capturing parentheses are more "greedy" than other quantifiers. For example, a(a)* will match "aaa" with cap(1) == "aaa". This behavior is different from what other regexp engines do (notably, Perl). To obtain a more intuitive capturing behavior, specify QRegExp::RegExp2 to the QRegExp constructor or call setPatternSyntax(QRegExp::RegExp2).

    Parenthesis may cause problems; but I did use QRegExp::RegExp2, but it didn't help.



  • You didn't specify any subexpressions (or capture groups or whatever you might call them) so the desired result is at rx.cap(0), not rx.cap(1).

    @
    ...
    std::cout << rx.cap(0).toStdString() << " ";
    ...

    35 625 2 125
    @

    EDIT Looks like you've already solved your initial problem.



  • Ahh... Got it. Thanks.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.