简体   繁体   中英

Find strings between two tags with regex in Qt

can anybody help me with this?

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 barENDSTARThi there!ENDSTARTstackoverflowrulezEND

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) gives me ALL the contend between the first and last tag

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

The code is much simple:

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

STARThi there!END

STARTstackoverflowrulezEND

Any help?

Thanks!

Use rx.setMinimal(true) with .* to make it lazy:

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

See the QRegExp::setMinimal docs :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM