Monday, May 21, 2007

QRegExp.indexIn

int QRegExp.indexIn (self, QString str, int offset = 0, CaretMode caretMode = QRegExp.CaretAtZero)

Attempts to find a match in str from position offset (0 by default). If offset is -1, the search starts at the last character; if -2, at the next to last character; etc.

Returns the position of the first match, or -1 if there was no match.

The caretMode parameter can be used to instruct whether ^ should match at index 0 or at offset.

You might prefer to use QString.indexOf(), QString.contains(), or even QStringList.filter(). To replace matches use QString.replace().

Example:

 QString str = "offsets: 1.23 .50 71.00 6.00";
QRegExp rx("\\d*\\.\\d+"); // primitive floating point matching
int count = 0;
int pos = 0;
while ((pos = rx.indexIn(str, pos)) != -1) {
++count;
pos += rx.matchedLength();
}
// pos will be 9, 14, 18 and finally 24; count will end up as 4

No comments: