ionagamed
ionagamed

Reputation: 536

QRegularExpression match position in the source string

For example I have a QString, and I do the search for mathes in a while. How can I retrieve the position at which the match was in the source string?

QString str = ...;
QRegularExpression re(...);
int pos = 0;
QRegularExpressionMatch match;
while ((match = re.match(str, pos)).hasMatch()) {
    setting new pos somehow
    ...
}

Upvotes: 2

Views: 3551

Answers (1)

peppe
peppe

Reputation: 22786

http://doc.qt.io/qt-5/qregularexpressionmatch.html :

In addition, QRegularExpressionMatch returns the substrings captured by the capturing groups in the pattern string. The implicit capturing group with index 0 captures the result of the whole match.

For each captured substring it is possible to query its starting and ending offsets in the subject string by calling the capturedStart() and the capturedEnd() function, respectively. The length of each captured substring is available using the capturedLength() function.

Example:

QRegularExpression re("\\d+");
QRegularExpressionMatch match = re.match("XYZabc123defXYZ");
if (match.hasMatch()) {
    int startOffset = match.capturedStart(); // startOffset == 6
    int endOffset = match.capturedEnd(); // endOffset == 9
    // ...
}

Upvotes: 3

Related Questions