From 9110d4f1ed65f02d8bbcb81ed0634d5a38c2bf9f Mon Sep 17 00:00:00 2001 From: Giuseppe D'Angelo Date: Sun, 14 Oct 2012 17:10:43 +0100 Subject: QString::contains overload that returns the match results This convenience overload allows one to write QRegularExpression re1, re2, ...; QRegularExpressionMatch match; QString subject; if (subject.contains(re1, &match)) { // ... } else if (subject.contains(re2, &match)) { // ... } // .. One can then inspect the results of a successful match in each block (as well as extracting the captured substrings, etc.). Change-Id: I0fb8be8b577656e8db994198f8105c26c4fe67b0 Reviewed-by: Lars Knoll Reviewed-by: Thiago Macieira --- src/corelib/tools/qstring.cpp | 27 +++++++++++++++++++++++++++ src/corelib/tools/qstring.h | 2 ++ 2 files changed, 29 insertions(+) (limited to 'src/corelib/tools') diff --git a/src/corelib/tools/qstring.cpp b/src/corelib/tools/qstring.cpp index 10ef6b34dd..a3036a3f24 100644 --- a/src/corelib/tools/qstring.cpp +++ b/src/corelib/tools/qstring.cpp @@ -3339,6 +3339,33 @@ bool QString::contains(const QRegularExpression &re) const return match.hasMatch(); } +/*! + \overload contains() + \since 5.1 + + Returns true if the regular expression \a re matches somewhere in this + string; otherwise returns false. + + If the match is successful and \a match is not a null pointer, it also + writes the results of the match into the QRegularExpressionMatch object + pointed by \a match. + + \sa QRegularExpression::match() +*/ + +bool QString::contains(const QRegularExpression &re, QRegularExpressionMatch *match) const +{ + if (!re.isValid()) { + qWarning("QString::contains: invalid QRegularExpresssion object"); + return false; + } + QRegularExpressionMatch m = re.match(*this); + bool hasMatch = m.hasMatch(); + if (hasMatch && match) + *match = m; + return hasMatch; +} + /*! \overload count() \since 5.0 diff --git a/src/corelib/tools/qstring.h b/src/corelib/tools/qstring.h index 574285fa1e..b7a08928b3 100644 --- a/src/corelib/tools/qstring.h +++ b/src/corelib/tools/qstring.h @@ -72,6 +72,7 @@ QT_BEGIN_NAMESPACE class QCharRef; class QRegExp; class QRegularExpression; +class QRegularExpressionMatch; class QString; class QStringList; class QTextCodec; @@ -339,6 +340,7 @@ public: int indexOf(const QRegularExpression &re, int from = 0) const; int lastIndexOf(const QRegularExpression &re, int from = -1) const; bool contains(const QRegularExpression &re) const; + bool contains(const QRegularExpression &re, QRegularExpressionMatch *match) const; int count(const QRegularExpression &re) const; #endif -- cgit v1.2.3