QString: fix count(QRegularExpression)
There is an off by one in the implementation of count(): a match must be attempted even at the very end of the string, because a 0-length match can happen there. While at it, improve the documentation on the counter-intuitive behavior of count(), which doesn't merely count how many times a regexp matches into a string using ordinary global matching. [ChangeLog][QtCore][QString] Fixed a corner case when using QString::count(QRegularExpression), causing an empty in the last position not to be accounted for in the returned result. Change-Id: I064497839a96979abfbac2d0a96546ce160bbc46 Pick-to: 5.15 6.0 Reviewed-by: Thiago Macieira <thiago.macieira@intel.com>bb10
parent
92c066b1e5
commit
7c3208c97d
|
|
@ -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;
|
||||
|
|
|
|||
|
|
@ -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");
|
||||
|
|
|
|||
Loading…
Reference in New Issue