qtqregularexpressionqstringlist

QStringList does not return index by QRegularExpression


What am I doing wrong? I want to find an index of a string, which matches given QRegularExpression, in QStringList.

#include <QCoreApplication>
#include <QStringList>
#include <QRegularExpression>
#include <QDebug>

 int main(int argc, char *argv[])
 {
    QCoreApplication a(argc, argv);

    QStringList list{"bla-bla-bla"};

    qDebug() //Prints "true"
        << QRegularExpression("bla-*").match(list[0]).hasMatch();
    qDebug() //Prints "-1", but I want it was "0" here
        << list.indexOf(QRegularExpression("bla-*"));

    return a.exec();
}

Solution

  • Firstly, consider your regular expression...

    bla-*
    

    QRegularExpression uses a Perl compatible syntax by default. That means the * character is a quantifier that requires zero or more of the preceding atom. In this case the atom in question is simply the preceding character: the -. So your regular expression is asking for the text bla followed by zero or more - characters.

    The documentation for QStringList::indexOf states (my emphasis)...

    Returns the index position of the first exact match of re in the list, searching forward from index position from. Returns -1 if no item matched

    It's slightly confusing but in this instance the phrase exact match appears to suggest that implicit begin and end anchors are assumed around the regular expression. Hence you're actually asking for a match for...

    ^bla-*$
    

    That is, the text bla at the beginning of the string followed by zero or more - characters and then the end of the string. So no match in this case. By switching to...

    bla-.*
    

    you ask for a match of bla- at the beginning of the string followed by zero or more characters of any value and finally the end of the string.