QRegularExpression 表示“仅空白字符”(从 QRegExp 替换)

问题描述 投票:0回答:1

我必须用

QRegExp
替换
QRegularExpression
,并且我对“字符串仅包含空白字符”进行了检查,但我不知道如何设置
QRegularExpression
来做同样的事情。这是一个示例代码(在注释中,我输入了结果 - 以及所需的结果)。

#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;
}
qt qregexp qregularexpression
1个回答
0
投票

正则表达式

\s*
表示“任意数量的空白字符”。当然,“任何数字”都可以为零,因此不带空格的字符串与此表达式匹配。该表达式按照您预期的
QRegExp
方式工作,因为它包含
exactMatch
方法,该方法有效地将
^
放置在表达式的开头(表示字符串的开头),并在末尾放置
$
表达式的(表示字符串的结尾)。这有效地使您的表达式
^\s*$
,这意味着“包含零个或多个空白字符的字符串”。

QRegularExpression
类已经废除了
exactMatch
方法。您可以使用旧的表达式调用
QRegularExpression::anchoredPattern
,也可以自己插入
^
,然后插入
$
。由于您的问题表明您对“仅包含空格字符”和 not 空字符串感兴趣,因此我建议使用
\s+
。如果您仍然对空字符串感兴趣,可以使用
\s*
。因此,您的选择要么只是使用
QRegularExpression
:

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

或使用

QRegularExpression::anchoredPattern
:

QString p("\\s+");
QRegularExpression whiteSpace(QRegularExpression::anchoredPattern(p));
© www.soinside.com 2019 - 2024. All rights reserved.