在Qt中使用正则表达式查找两个标签之间的字符串 [英] Find strings between two tags with regex in Qt

查看:1606
本文介绍了在Qt中使用正则表达式查找两个标签之间的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以帮我吗?

我有一个包含N个子字符串的字符串,该字符串由标签分隔,我必须获取所有子字符串.字符串就像

I have a string which contains N substrings, delimited by tags and I have to get ALL of the substrings. The string is like

STARTfoo barENDSTART在那里嗨!ENDSTARTstackoverflowrulezEND

STARTfoo barENDSTARThi there!ENDSTARTstackoverflowrulezEND

我想获取START/END标记之间的所有字符串,我尝试了几个没有运气的正则表达式:

I would like to get all the strings between START/END tags, I tried with a couple of regular expressions with no luck:

(START)(.*)(END)为我提供了第一个标签和最后一个标签之间的所有竞争

(START)(.*)(END) gives me ALL the contend between the first and last tag

(START)(\ w +)(END)没有结果

(START)(\w+)(END) gives me no result

代码很简单:

QString l_str "STARTfoo barENDSTARThi there!ENDSTARTstackoverflowrulezEND"; 
QRegExp rx("(START)(\w+)(END)");
QStringList list;
int pos = 0;
while ((pos = rx.indexIn(l_str, pos)) != -1)
{
    list << rx.cap(1);
    pos += rx.matchedLength();
}
qWarning() << list;

我想要一个类似的结果列表:

I'd like a resulting list like:

STARTfoo barEND

STARTfoo barEND

STARThi在那里!END

STARThi there!END

STARTstackoverflowrulezEND

STARTstackoverflowrulezEND

有帮助吗?

谢谢!

推荐答案

使用rx.setMinimal(true).*使其变得懒惰:

QRegExp rx("START.*END");
rx.setMinimal(true);

请参见 QRegExp::setMinimal文档:

启用或禁用最小匹配.如果 minimal false,则匹配为贪婪(最大),这是默认设置.

Enables or disables minimal matching. If minimal is false, matching is greedy (maximal) which is the default.

这篇关于在Qt中使用正则表达式查找两个标签之间的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆