QRegularExpression: add captureCount()

QRegularExpression::captureCount() returns the number of
capturing groups inside the regular expression pattern.

Change-Id: Ib90ce67c67d06ab2966f0c98bd91da21defc156d
Reviewed-by: Thiago Macieira <thiago.macieira@intel.com>
This commit is contained in:
Giuseppe D'Angelo 2012-02-19 23:56:50 +01:00 committed by Qt by Nokia
parent 1899861858
commit efcd4d9470
3 changed files with 46 additions and 0 deletions

View File

@ -1340,6 +1340,19 @@ void QRegularExpression::setPatternOptions(PatternOptions options)
d->patternOptions = options;
}
/*!
Returns the number of capturing groups inside the pattern string,
or -1 if the regular expression is not valid.
\sa isValid()
*/
int QRegularExpression::captureCount() const
{
if (!isValid()) // will compile the pattern
return -1;
return d->capturingCount;
}
/*!
Returns true if the regular expression is a valid regular expression (that
is, it contains no syntax errors, etc.), or false otherwise. Use

View File

@ -94,6 +94,8 @@ public:
int patternErrorOffset() const;
QString errorString() const;
int captureCount() const;
enum MatchType {
NormalMatch = 0,
PartialPreferCompleteMatch,

View File

@ -73,6 +73,8 @@ private slots:
void serialize();
void operatoreq_data();
void operatoreq();
void captureCount_data();
void captureCount();
private:
void provideRegularExpressions();
@ -1198,6 +1200,35 @@ void tst_QRegularExpression::operatoreq()
}
}
void tst_QRegularExpression::captureCount_data()
{
QTest::addColumn<QString>("pattern");
QTest::addColumn<int>("captureCount");
QTest::newRow("captureCount01") << "a pattern" << 0;
QTest::newRow("captureCount02") << "a.*pattern" << 0;
QTest::newRow("captureCount03") << "(a) pattern" << 1;
QTest::newRow("captureCount04") << "(a).*(pattern)" << 2;
QTest::newRow("captureCount05") << "^(?<article>\\w+) (?<noun>\\w+)$" << 2;
QTest::newRow("captureCount06") << "^(\\w+) (?<word>\\w+) (.)$" << 3;
QTest::newRow("captureCount07") << "(?:non capturing) (capturing) (?<n>named) (?:non (capturing))" << 3;
QTest::newRow("captureCount08") << "(?|(a)(b)|(c)(d))" << 2;
QTest::newRow("captureCount09") << "(?|(a)(b)|(c)(d)(?:e))" << 2;
QTest::newRow("captureCount10") << "(?|(a)(b)|(c)(d)(e)) (f)(g)" << 5;
QTest::newRow("captureCount11") << "(?|(a)(b)|(c)(d)(e)) (f)(?:g)" << 4;
QTest::newRow("captureCount_invalid01") << "(.*" << -1;
QTest::newRow("captureCount_invalid02") << "\\" << -1;
QTest::newRow("captureCount_invalid03") << "(?<noun)" << -1;
}
void tst_QRegularExpression::captureCount()
{
QFETCH(QString, pattern);
QRegularExpression re(pattern);
QTEST(re.captureCount(), "captureCount");
if (!re.isValid())
QCOMPARE(re.captureCount(), -1);
}
QTEST_APPLESS_MAIN(tst_QRegularExpression)
#include "tst_qregularexpression.moc"