Is there any difference between QRegularExpression and QRegExp?

前端 未结 2 1222
面向向阳花
面向向阳花 2021-01-03 17:48

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 al

相关标签:
2条回答
  • 2021-01-03 18:09

    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.

    0 讨论(0)
  • 2021-01-03 18:11

    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.

    0 讨论(0)
提交回复
热议问题