Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

removing characters from string to keep digits



  • vers ="VER 3.3a on ABC"
    #Then I try to remove all chars except ".0123456789"
    vers.remove(QRegularExpression("[-`~!@#$%^&*()_—+=|:;<>«»,?/{}'"[]\]"));
    #hoping that I can do vers.toFloat() and get 3.3

    But vers is untouched.. Qt 5.11.3 / 5.12.6
    What is the correct way to extract the version number in this case?


  • Moderators

    QString result;
    for (const QChar c : qAsConst(vers)) {
      if (c.isDigit() || c == '.') {
        result.append(c);
      }
    }
    

  • Moderators

    QString result;
    for (const QChar c : qAsConst(vers)) {
      if (c.isDigit() || c == '.') {
        result.append(c);
      }
    }
    


  • Thank you !



  • @Andse
    Apart from doing it @sierdzio's way --- which is certainly much better than attempting to enumerate a whole bunch of characters to remove in order to be left with only digits --- in answer to your question, your regular expression looks malformed to me, where you try to specify " and ] characters. (In fact, copying what you have here gives an "unterminated expression", so not sure what exactly you have.) That part would need to be (untested):

    QRegularExpression("[...\"\\]]")
    

    Because of your ]] ( <-- damn :( this comes out right in edit mode, but not after posting :( ), where it should be \\]], I suspect you have something like the character class enclosed by [...] followed by something to do with \\ or ], and that's why it does not match.


Log in to reply