Find sequence in QString



  • Hi,

    In a .txt file i need to find a specific sequence in a line.

    The lines which i need to detect are:

      0: -0,385236
      1: 0,141017
      2: 4,39365
      3: 12,0689
      4: 7,32349
      5: -4,69991
      6: -1,30162
    

    Sequence: Space - Integer - Double Point - Space - Float Number

    I started to read each line of the file. But i have no clue how to detect this sequence.

    QFile file("file.txt");
    if (!file.open()) {
       QTextStream stream(&file);
       forever {   
          QString line = stream.readlLine();
          if (line.isNull())
             break;
    
        // now detect the sequence
       }
    }
    

    I'm not sure if i can use the QRegExp class.

    Thanks for help!


  • Moderators

    @beecksche
    use QRegularExpression:

    QRegularExpression rx("([0-9])+:\\s(\\-?[0-9]+,[0-9]+)");
    QRegularExpressionMatch match = rx.match( line ); // line == "5: -4,69991"
    if (match.hasMatch())
    {
        QString id = match.captured(0); // id == "5"
        QString value = match.captured(1); // value == "-4,69991"
        // ...
    }
    


  • @raven-worx

    Thanks a lot!

    In the captured() function i had to change the argument:

            QString id = match.captured(1); // id == "5"
            QString value = match.captured(2); // value == "-4,69991"
    

    Edit:

    To use it, i also had to change the expressio to:

    QRegularExpression rx("([0-9]+):\\s(\\-?[0-9]+,[0-9]+)");
    

    to get the first integers bigger the 10.


Log in to reply
 

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