qtqregexpqregularexpression

QRegularExpression for "only white space characters" (Replacement from QRegExp)


I must replace the QRegExp with QRegularExpression, and I had the check for "a string contains only white space characters" working, but I don't know how to set QRegularExpression to do the same thing. Here is a sample code (in comments, I put the result - and the desired result).

#include <QCoreApplication>
#include <QDebug>
#include <QRegExp>
#include <QRegularExpression>

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    QString inputString1 = "thisisatest";
    QString inputString2 = "this is a test";
    QString inputString3 = " \n\t";

    // How do I make this work the same as QRegExp ?
    QRegularExpression whiteSpace(QStringLiteral("\\s*"));
    qDebug() << whiteSpace.match(inputString1).hasMatch();  // Weird !!! says true. Should be false
    qDebug() << whiteSpace.match(inputString2).hasMatch();  // Says true. There are some spaces. But I want something that would be false
    qDebug() << whiteSpace.match(inputString3).hasMatch();  // I only want this string to return true, how do I do it ?

    // This is the old behavior that I want to keep
    QRegExp whiteSpace1(QStringLiteral("\\s*"));
    qDebug() << whiteSpace1.exactMatch(inputString1);       // False
    qDebug() << whiteSpace1.exactMatch(inputString2);       // False
    qDebug() << whiteSpace1.exactMatch(inputString3);       // True

    return 0;
}

Solution

  • The regular expression \s* means "any number of whitespace characters". Of course, "any number" could be zero, so a string with no spaces matches this expression. This expression worked the way that you intended with QRegExp because it contained an exactMatch method, which effectively placed a ^ at the beginning of the expression (meaning the beginning of a string) and a $ at the end of the expression (meaning the end of a string). This effectively made your expression ^\s*$, which means "a string containing zero or more whitespace characters".

    The QRegularExpression class has done away with the exactMatch method. You can either call QRegularExpression::anchoredPattern with your old expression or just insert the ^ and then $ yourself. Since your question states that you are interested in strings that "contains only whitespace characters" and not empty strings, I recommend using \s+. If you are still interested in empty strings, you can use \s*. As such, your options are either just using QRegularExpression:

    QRegularExpression whiteSpace(QStringLiteral("^\\s+$"));
    

    or use QRegularExpression::anchoredPattern:

    QString p("\\s+");
    QRegularExpression whiteSpace(QRegularExpression::anchoredPattern(p));