PDA

View Full Version : Recover a QString with QRegExp



hassinoss
26th February 2014, 14:19
I want to recover a QString between brakets.

For example i have "Cos([Temperature1]*25)+58" and i want recover just "[Temperature1]*25" ,

can i do it with a QRegExp or is there a best way?

Thanks!

wysota
26th February 2014, 14:42
Yes, you can do it with a regular expression.

The following regexp should match your case:

QRegExp(".*\(([^)]*\).*");

hassinoss
26th February 2014, 15:09
i tried it but it doesn't work :(

i tried this :

QString formule = "Cos([Temperature1]*25)+58" ;
QStringList listMul;
QRegExp regExp ("(\[(.*?)\])");
listMul = formule.split(regExp);

and i find in the list Cos, [Temperature1] , 25 and +58 but when i changed * by + i find Cos, [Temperature1]+25 and +58.

I want the same thing with * : Cos, [Temperature1]*25 and +58.

anda_skoa
26th February 2014, 20:01
You can also use indexOf() to search for the opening parenthese, then indexOf with that start index to search for the closing parentheses and then use QString::mid() to get the part that is of interest to you.

Cheers,
_

ChrisW67
27th February 2014, 02:49
i tried it but it doesn't work :(
Wysota's suggestion is not quite right but it really doesn't matter because what you asked for was not what you wanted anyway.

You actually wanted to split the expression into tokens. This a non-trivial exercise in general cases, but for your specific case this works:


QString formule = "Cos([Temperature1]*25)+58" ;

// The incredibly simple
QStringList list = formule.split(QRegExp("[()]"));
qDebug() << list;

// or the more involved but more flexible
list.clear();
const QRegExp re("[^()]+");
int pos = 0;
while ((pos = re.indexIn(formule, pos)) != -1) {
list << re.cap(0);
pos += re.matchedLength();
};
qDebug() << list;

hassinoss
27th February 2014, 16:04
Thanx for your replies , they were very useful