Find strings between two tags with regex in Qt

2020-04-14 03:38发布

问题:

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!

回答1:

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.