diff --git a/src/corelib/text/qstring.cpp b/src/corelib/text/qstring.cpp index 56d9e0a011..02501e00f4 100644 --- a/src/corelib/text/qstring.cpp +++ b/src/corelib/text/qstring.cpp @@ -4324,10 +4324,16 @@ bool QString::contains(const QRegularExpression &re, QRegularExpressionMatch *rm Returns the number of times the regular expression \a re matches in the string. - This function counts overlapping matches, so in the example - below, there are four instances of "ana" or "ama": + For historical reasons, this function counts overlapping matches, + so in the example below, there are four instances of "ana" or + "ama": \snippet qstring/main.cpp 95 + + This behavior is different from simply iterating over the matches + in the string using QRegularExpressionMatchIterator. + + \sa QRegularExpression::globalMatch() */ qsizetype QString::count(const QRegularExpression &re) const { @@ -4338,7 +4344,7 @@ qsizetype QString::count(const QRegularExpression &re) const qsizetype count = 0; qsizetype index = -1; qsizetype len = length(); - while (index < len - 1) { + while (index <= len - 1) { QRegularExpressionMatch match = re.match(*this, index + 1); if (!match.hasMatch()) break; diff --git a/tests/auto/corelib/text/qstring/tst_qstring.cpp b/tests/auto/corelib/text/qstring/tst_qstring.cpp index 04a4469a7d..7c965129f0 100644 --- a/tests/auto/corelib/text/qstring/tst_qstring.cpp +++ b/tests/auto/corelib/text/qstring/tst_qstring.cpp @@ -1714,6 +1714,7 @@ void tst_QString::count() QCOMPARE(a.count("FG",Qt::CaseInsensitive),3); QCOMPARE(a.count( QString(), Qt::CaseInsensitive), 16); QCOMPARE(a.count( "", Qt::CaseInsensitive), 16); + QCOMPARE(a.count(QRegularExpression("")), 16); QCOMPARE(a.count(QRegularExpression("[FG][HI]")), 1); QCOMPARE(a.count(QRegularExpression("[G][HE]")), 2); QTest::ignoreMessage(QtWarningMsg, "QString::count: invalid QRegularExpression object");