[Solved] Simple Regex assistance

  • I've been trying to capture some digits within a string from the output of fdisk. Here is the input string:

    QString s = Disk /dev/mmcblk2: 3.6 GiB, 3867148288 bytes, 7553024 sectors

    My target capture is the 3.6 GiB number. I have been trying:

    QRegExp rx("^\b*\bG");
    qDebug() << "Captured: " + rx.cap(0);

    I figured that I could apply a word/letter boundary on the colon or partition location and then another boundary on the GiB string.

  • HI,

    your RegExp is wrong

    this program

    #include <QCoreApplication>
    #include <QtDebug>
    int main(int argc, char *argv[])
        QCoreApplication a(argc, argv);
        QString s = "Disk /dev/mmcblk2: 3.6 GiB, 3867148288 bytes, 7553024 sectors";
        QRegExp rx("([\\d\\.]+) GiB");
        qDebug() << rx.indexIn(s);
        qDebug() << "Captured: " + rx.cap(1);

    works as you expect.

    NOTE: rx.cap(0) returns the whole string matching the RegExp; rx.cap(1) the captured group ()

  • Lifetime Qt Champion


    When dealing with QRegExp you can use the regexp example in examples/tools. It's a simple yet pretty nice application to test your regexp.

    If you are using Qt 5, you should consider QRegularExpression. Since Qt 5.5 there's also the helper tool that you can use to build your regexp.

  • @SGaist said:

    Since Qt 5.5 there's also the helper tool that you can use to build your regexp.

    What's that tool??

  • Lifetime Qt Champion

    The name's "regularexpression" but after a double check, it might have missed the 5.5 window, it's in the dev branch here but compilable without any problem with "older" releases

  • ok thanks, is an example

  • Lifetime Qt Champion

    I'd say the folder name is a bit misleading in this case

Log in to reply

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