Extract a QString with a regular expression.
-
@Patou355
well im not sure how complex the input will be.
For a fast solution, i would just split at space and check the entries.
If not ending in ' it was falsely split and should be merged with next.
if format always is like shown. its very easy to fix up. -
Hi,
Do you mean the pattern is
one uppercased letter between two single quotes
? -
@SGaist the pattern can be anything between the double quotes. That's why I replaced the "A" with "Johnny Clegg" ;)
I could split on the spaces but the issue here is that I would get
Johnny
Clegg
B
C
and so oninstead of the
Johnny Clegg
B
C
and so on
that I want. -
@Patou355
ok, how about this:Search the string for [ and ] and remove those and everything in between
int start = myString.indexOf('['); int end = myString.indexOf(']'); if(start != -1 && end != -1){ myString.replace(start, end-start, ''); }
Now split over
' '
. -
Something like ?
QRegularExpression rx("\"(\\w*\\s?\\w*)\""); QRegularExpressionMatchIterator rxIterator = rx.globalMatch(yourCoolString); QStringList words; while (rxIterator.hasNext()) { QRegularExpressionMatch match = rxIterator.next(); QString word = match.captured(1); words << word; }
[edit: Fixed double quote escaping SGaist]
-
I wrote this function which looks a lot like @SGaist's one and that works:
/*Create a QStringList from the extraction of a QRegularExpression*/ static QStringList extractStr(const QString &s, QRegularExpression delim){ QStringList output; QString buff; QRegularExpressionMatchIterator i = delim.globalMatch(s); while (i.hasNext()) { QRegularExpressionMatch match = i.next(); if (match.hasMatch()) { buff = match.captured(0); output.push_back(buff); } } return output; }
Thanks to all of you for your help :)
Patrick. -
One small note, you are wasting CPU cycle here. The
QRegularExpressionMatchIterator
returns only match objects that contains a match thus the if is useless.