Uploaded image for project: 'Qt'
  1. Qt
  2. QTBUG-103103

QRegularExpressionMatch::capturedTexts list does not contain empty strings if they are at the end

    XMLWordPrintable

Details

    • Bug
    • Resolution: Invalid
    • Not Evaluated
    • None
    • 5.15
    • None
    • All

    Description

      Not sure if this is actually a bug. If not, the documentation could be clearer.

      When migrating some old code from QRegExp to QRegularExpression, I noticed that capturedTexts returns a differently sized list for the same use case. The attached code example shows this behavior. For the first text input, the last two capture groups are empty. QRegExp includes them as empty strings in the returned list. QRegularExpressionMatch however, simply returns a list with fewer elements.
      The expectation would be that each capture group is included, even if empty.

      #include <QDebug>
      #include <QRegExp>
      #include <QRegularExpression>
      #include <QString>
      
      static void testQRegExp(const QString &regex, const QString &text) {
        QRegExp regExp{regex};
      
        auto index = regExp.indexIn(text);
        Q_ASSERT(index == 0);
        qDebug() << regExp.capturedTexts();
      }
      
      static void testQRegularExpression(const QString &regex, const QString &text) {
        auto match = QRegularExpression{regex}.match(text);
        Q_ASSERT(match.hasMatch());
        qDebug() << match.capturedTexts();
      }
      
      int main(int argc, char *argv[]) {
        auto regex = QStringLiteral(R"(([a-z]*)=([a-z]+)(\|(.*)){0,1})");
        auto text1 = QStringLiteral("test=abc");
        auto text2 = QStringLiteral("test=abc|def");
      
        qDebug() << "### QRegExp:";
        testQRegExp(regex, text1);
        testQRegExp(regex, text2);
        qDebug() << "### QRegularExpression:";
        testQRegularExpression(regex, text1);
        testQRegularExpression(regex, text2);
      }
      

      The output of that program is this:

      ### QRegExp:
      ("test=abc", "test", "abc", "", "")
      ("test=abc|def", "test", "abc", "|def", "def")
      ### QRegularExpression:
      ("test=abc", "test", "abc")
      ("test=abc|def", "test", "abc", "|def", "def")
      

      Attachments

        No reviews matched the request. Check your Options in the drop-down menu of this sections header.

        Activity

          People

            peppe Giuseppe D'Angelo
            lbuckel Leon Buckel
            Votes:
            0 Vote for this issue
            Watchers:
            3 Start watching this issue

            Dates

              Created:
              Updated:
              Resolved:

              Gerrit Reviews

                There are no open Gerrit changes