例如,我有一个 QString,我会花一段时间搜索数学。如何检索匹配项在源字符串中的位置?
QString str = ...;
QRegularExpression re(...);
int pos = 0;
QRegularExpressionMatch match;
while ((match = re.match(str, pos)).hasMatch()) {
setting new pos somehow
...
}
最佳答案
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.
示例:
QRegularExpression re("\\d+");
QRegularExpressionMatch match = re.match("XYZabc123defXYZ");
if (match.hasMatch()) {
int startOffset = match.capturedStart(); // startOffset == 6
int endOffset = match.capturedEnd(); // endOffset == 9
// ...
}
关于c++ - QRegularExpression 源字符串中的匹配位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28725588/