我可以找到与此匹配的上一个匹配项,但是我无法做到的是捕获匹配字符串的长度:

int pos = 0;

if((pos = text.lastIndexOf(QRegularExpression(pattern), cursorPosition - 1)) != -1))
    cout << "Match at position: " << pos << endl;

我可以使用QRegularExpressionMatch捕获匹配的长度,但是在QRegularExpressionQRegularExpressionMatch类中找不到任何会改变搜索方向的标志/选项。 (我并不是要反转模式,而是要在字符串中某个位置之前找到第一个匹配项。)

示例(我想查找非偶数正则表达式"hello"):
    hello world hello
            ^
          start (somewhere in the middle)

这应该是匹配的部分:
   hello world hello
   ^   ^
start  end

先感谢您。

最佳答案

请注意,在Qt5中QRegExp!= QRegularExpression,我对QRegExp更加熟悉。就是说,我看不到使用QRegularExpression或QRegularExpression::match()做所需的方法。

相反,我将使用QString::indexOf向前搜索,并使用QString::lastIndexOf向后搜索。如果您只想查找偏移量,则可以使用QRegExp或QRegularExpression进行此操作。

例如,

int pos = 8;
QString text = "hello world hello";
QRegularExpression exp("hello");

int bwd = text.lastIndexOf(exp, pos);   //bwd = 0
int fwd = text.indexOf(exp, pos);       //fwd = 12

//"hello world hello"
// ^       ^   ^
//bwd     pos fwd

但是,您还希望使用捕获的文本,而不仅仅是知道它在哪里。这是QRegularExpression似乎失败的地方。据我所知,在调用QString::lastIndexOf()QRegularExpress之后,没有lastMatch()检索匹配的字符串。

但是,如果改用QRegExp,则可以执行以下操作:
int pos = 8;
QString text = "hello world hello";
QRegExp exp("hello");

int bwd = text.lastIndexOf(exp, pos);   //bwd = 0
int fwd = text.indexOf(exp, pos);       //fwd = 12

//"hello world hello"
// ^       ^   ^
//bwd     pos fwd

int length = exp.cap(0).size();     //6... exp.cap(0) == "hello"
//or, alternatively
length = exp.matchedLength();       //6

传递给QString方法的QRegExp对象将使用捕获的字符串进行更新,然后可以使用和操作。我无法想象他们忘记了使用QRegularExpression做到这一点,但是看起来他们可能这样做了。

关于c++ - QRegularExpression-查找向后捕获长度的匹配项,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29900791/

10-11 07:37