我可以找到以前的匹配,但我不能这样做,就是捕获匹配字符串的长度:
int pos = 0;
if((pos = text.lastIndexOf(QRegularExpression(pattern), cursorPosition - 1)) != -1))
cout << "Match at position: " << pos << endl;我可以用QRegularExpressionMatch捕获匹配的长度,但是在QRegularExpression或QRegularExpressionMatch类中找不到任何会改变搜索方向的标志/选项。(我并不是想逆转模式,而是在字符串中的某个位置之前找到第一次匹配。)
示例(我希望找到非偶数正则表达式"hello"):
hello world hello
^
start (somewhere in the middle)这应该是匹配的部分:
hello world hello
^ ^
start end提前谢谢你。
发布于 2015-04-27 18:07:59
请注意,在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() lastMatch() QRegularExpress之后,没有任何QRegularExpress()可以检索匹配的字符串。
但是,如果您使用的是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传递给QRegExp方法的QString对象将被更新为捕获的字符串,然后可以使用和操作该字符串。我无法想象他们忘了用QRegularExpression做这件事,但是看起来他们可能已经忘记了。
发布于 2016-10-24 00:35:15
这可以用QRegularExpression来完成。只需使用方法
QRegularExpressionMatch QRegularExpression::match(const QString &subject, int offset = 0, MatchType matchType = NormalMatch, MatchOptions matchOptions = NoMatchOption) const
然后调用方法capturedLen(int)、capturedStart(int)和类似的结果。
链接:
http://doc.qt.io/qt-5/qregularexpression.html#match
http://doc.qt.io/qt-5/qregularexpressionmatch.html
https://stackoverflow.com/questions/29900791
复制相似问题