Extract a QString with a regular expression.
-
Hi all!
I'm trying to do the followin :
I have a QString str containing exactly what follows :
[1] "Johnny Clegg" "B" "C" "D" "E" "F" "G" "H"
And I want to get a QStringList containing :Johnny Clegg
B
C
D
E
F
G
Hthe split function doesn't match what I need because I want to extract a pattern and not split from a pattern. The problem with splitting is that the first part containing [1] " will be with Johnny Clegg in the first item of the QStringList
So the question: how to make a QStringList from a pattern extraction in a simple way? maybe as simple as QString::split ?
-
@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.