QRegularExpression Problem



  • I am trying a simple pattern to extract numbers from a ASCII text file. The code I am using

    QTextStream in( &file );
    QString line = in.readline();
    QRegularExpression re;
    re.setPattern ( " -?[0-9]+\.?[0-9]* ");
    line.section(re, 0);

    a testing line was:
    "Expected Vibration Frequency = 2.52 MHz"

    Using RegexBuddy I tested the pattern and the results were
    2.52.

    However, when I implement the above code I get
    2.52 Mhz

    I tried the Qt expression of -?\d*\.?\d* and got the same thing. Why are the ascii characters after the digits included?


  • Moderators

    welcome to devnet

    My guess is that the syntax handling used is different. You need to check the documentation of "QRegularExpression":http://qt-project.org/doc/qt-5/qregularexpression.html

    I have never used it. It has been implemented for Qt5. The older version "QRegExp":http://qt-project.org/doc/qt-5/QRegExp.html is also still available.There you have different possibilities.

    The "example code for QRegExp":http://qt-project.org/doc/qt-5/qtwidgets-tools-regexp-example.html is a handy tool to check different possibilities. Unfortunately, it is still based on the older QRegExp.


  • Lifetime Qt Champion

    Hi and welcome to devnet,

    I'd say you are using the wrong tool:

    @
    QString line("Expected Vibration Frequency = 2.52 MHz");
    QRegularExpression re;
    re.setPattern ( "-?[0-9]+\.?[0-9]*");
    QRegularExpressionMatch match = re.match(line);
    qDebug() << match.captured();
    @

    And you'll get 2.52

    Hope it helps



  • Thanks for the help. I had not tried to use the QRegularExpressionMatch. Changing code as your example showed solved the problem.

    Best,


Log in to reply
 

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