Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any difference between QRegularExpression and QRegExp?

Tags:

c++

qt

qt5

qregexp

I see there is a new class for regular expressions - QRegularExpression. Is it just a typedef for QRegExp, or a new class, or what? And why do we need it, we already have QRegExp?

like image 219
sashoalm Avatar asked Apr 09 '15 07:04

sashoalm


2 Answers

Ok, after some more digging into the docs, I found it really is a new class, it has improvements, but it is only available in Qt5, so you can't use it if you want to compile on both Qt4 and Qt5:

Notes for QRegExp Users

The QRegularExpression class introduced in Qt 5 is a big improvement upon QRegExp, in terms of APIs offered, supported pattern syntax and speed of execution. The biggest difference is that QRegularExpression simply holds a regular expression, and it's not modified when a match is requested. Instead, a QRegularExpressionMatch object is returned, in order to check the result of a match and extract the captured substring. The same applies with global matching and QRegularExpressionMatchIterator.

like image 131
sashoalm Avatar answered Sep 16 '22 22:09

sashoalm


At least for Qt 4.8. I can give a very practical reason to use QRegularExpressions instead of QRegExp:

Do these look dangerous to you?

int index = myQString.indexOf(myQRegExp); bool okay = myQString.contains(myQRegExp); 

Both lines can corrupt your heap, crash or hang your application. I experienced heap corruption and hang with Qt 4.8. The blog post QString::indexOf() versus Qt 4.5 explains that QString::indexOf() modifies a const QRegExp object. QString::contains() inlines QString::indexOf() so it's the same problem.

If you're stuck with Qt4 and thus QRegExp, you could use

int index = myQRegExp.indexIn(myQString); bool okay = (myQRegExp.indexIn(myQString) != -1);  

in your sources instead. Or patch the Qt Sources.

like image 34
Sascha Avatar answered Sep 16 '22 22:09

Sascha