Search code examples
qtqstring

Count QString arguments


Do you know how to get the count of possible arguments in a QString?

I want to do something like:

int argumentCount = countArguments(QString("This is the %1 argument, this is the %2 one")`);

where the result should be argumentCount == 2.


Solution

  • You can use regular expressions and QString::count function:

    QString str1("%1%2 test test %3 %4 %555");
    int n = str1.count(QRegExp("%\\d+"));//n == 5
    

    Update: Because QString's arg numbers can be in 1-99 range this reg-exp can be used:

    QString str1("%1%2 test test %3 %4 %555");
    int n = str1.count(QRegExp("%\\d{1,2}(?!\\d)"));//n == 4