Giancarlo Giancarlo - 2 months ago 8
C++ Question

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:


STARThi there!END


Any help?



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

QRegExp rx("START.*END");

See the QRegExp::setMinimal docs:

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