PDA

View Full Version : QRegExp: get the parsed string



trallallero
4th April 2012, 15:26
I have for example this string:
"DLH3029 (LUFTHANSA THREE ZERO TWO NINER)"

that should become:
'LUFTHANSA THREE ZERO TWO NINER'

so I use this regex:

echo "DLH3029 (LUFTHANSA THREE ZERO TWO NINER)" | sed "s/[^(]*(\([^)]*\)).*/'\1'/"

How can now use it in a Qt program ?

I've tried but I cannot find a way to make it work.

Lykurg
4th April 2012, 15:45
QString::replace() or QRegExp, QRegExp::capturedTexts().

trallallero
4th April 2012, 16:07
Thanks but:


QRegExp rx("s/[^(]*(\([^)]*\)).*/'\1'/");
rx.indexIn("DLH3029 (LUFTHANSA THREE ZERO TWO NINER)");
QStringList list = rx.capturedTexts();
qDebug() << "list: " << list;
::exit(1);

result:

list: ("", "", "")

What am I doing wrong ?

Lykurg
4th April 2012, 18:15
Ehm s/[^(]*(\([^)]*\)).*/'\1'/ are two "commands". One for searching and one for replacing. For Qt you have to split them. QRegExp expects the search part. And also note that they are not 100% Perl compatible, but that is all in the docs... (Qt5 supports 100% Perl compatible expressions, if you want to use the newly published Alpha release.)

trallallero
4th April 2012, 19:44
Ah ok. The regex is a part of a bigger one so I have to split it further.
My company is thinking about upgrading to Qt5 so this is a good reason to do it now.

Thanks a lot Lykurg.

ChrisW67
5th April 2012, 01:02
Upgrading a commercial development project to alpha software is probably not the best idea. Nothing in your requirement needs the Perl regex compatibility changes AFAICT.

Also, be careful to escape backslashes in the string literals.

Lykurg
5th April 2012, 06:18
I don't have the URL's right now, but there was a test that the QRegExp class is really slow. That was also the reason for changing this class in Qt5. So even if you do not need the additional syntax a change to Qt5 (when ready) can pay off, if your application heavily rely on regular expressions.

EDIT: That was not the URL I was thinking of but anyway: http://qt-project.org/wiki/Regexp_engine_in_Qt5