QString - Removing non-alphanumeric chars



  • I am using this function to remove non-alphanumeric from a QString. I use this function before saving to a file on the OS, I need this since theses char are not permitted by the OS for a filename.

    With this function (code under), The compiler is giving me warning that I would like to fix:
    warning: C4129: '[' : unrecognized character escape sequence
    warning: C4129: ']' : unrecognized character escape sequence

    Or maybe there is a function like this that already exists in QString or QFile?
    Thank you!

    QString Util::cleanQString(QString toClean) {  
        QString toReturn = toClean;
        toReturn.remove(QRegExp(QString::fromUtf8("[-`~!@#$%^&*()_—+=|:;<>«»,.?/{}\'\"\\[\\]\\\]")));
        return toReturn;
    }


  • @maximus You don't directly escape the "[" and "]", so "\[", not "\\[". The pattern string you want to use is "[-`~!@#$%^&*()_—+=|:;<>«»,.?/{}\'\"\[\]\\\]".



  • Thanks you, that fixed the error.
    QRegex are always like writting chinese to me


  • Lifetime Qt Champion

    Hi,

    If I may, you should change for QRegularExpression (the regexp itself doesn't change). It has better performances.

    To help you build your regex, there's the regex example that you can use that provides a good starting point to write them.

    For QRegularExpression, you need to get the 5.6 sources to get the equivalent helper program.


Log in to reply
 

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