PDA

View Full Version : split camel case string



GrahamLabdon
1st February 2011, 14:44
Hi
Say I have a string "TopBanana"
What is the best way to split it into two strings "Top" and "Banana"
I tried with QRegExp but i dont think im using it correctly


QString s = QString("TopBanana");

QRegExp re = QRegExp("[A-Z}");

QStringList sl = s.split(re);



TIA

Graham

high_flyer
1st February 2011, 15:27
is "[A-Z}" a typo?
Didn't you mean "[A-Z]"?

majorwoody
1st February 2011, 15:30
You wrote QRegExp("[A-Z}"); - it should be QRegExp("[A-Z]");

You can try this:

QString s = QString("TopBanana");
QRegExp re1 = QRegExp("([A-Z])([a-z]*)");
s.replace(re1, ";\\1\\2");
QStringList sl = s.split(";");

Lykurg
1st February 2011, 15:47
beside the typo, you have to use a positive lookahead:
QString s = QString("TopBanana");
QStringList sl = s.split(QRegExp("(?=[A-Z])"), QString::SkipEmptyParts);

GrahamLabdon
1st February 2011, 16:22
Hi thanks
This solution works but the split gives me 3 strings in the list the first of which is empty

Lykurg
1st February 2011, 16:37
This solution works but the split gives me 3 strings in the list the first of which is emptyYes, and that is the reason why I passed QString::SkipEmptyParts ad a second parameter to the split function!