c++ - QRegularExpression 源字符串中的匹配位置

标签 c++ qt

例如,我有一个 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/

相关文章:

c++ - 如何在 mfc CListCtrl 中实现简单的复制/粘贴功能?

c++ - autoconf 和 automake 的通配符

c++ - Qt QProcess怎么写到standard中?

C++ 选择文件夹,包含文件

c++ - 就时间复杂度而言,可以更快地找到另一个字符串中的最小周期字符串吗

c++ - iostream 和 iostream.h 之间的区别

c++ - 如何将 Objective C 的类实例传递给 C++ 方法?

android - 交换 GridView 中的元素

qt - QtWebkit:控制台应用程序

c++ - 没有匹配函数来调用 Std::find?