[Qt-interest] more hits on QRegExp

Stephen Jackson spjackson42 at gmail.com
Wed Jul 22 22:36:53 CEST 2009


On Sun, Jul 19, 2009 at 8:22 PM, Frank Lutz wrote:
> Hi,
>
> i do have a string with the syntax:
>
> ...
> <xyz>A</xyz>
> <xyz>B</xyz>
> <xyz>C</xyz>
> ...
>
> now i want get the values with:
> QRegExp exp;
> exp.setPattern(".*<xyz>(.*)</xyz>.*");
> exp.exactMatch(str);
>
> for(int i=0;i<10;i++){
>        qDebug()<<exp.cap(i);
> }
>
> But it didn't work well :think:
>
> So could you give me please a tip! :D
>
> thanks very!

One issue you have is that "*" is greedy by default: it consumes as
much as it can, so it will potentially consume (multiple) "<xyz>"
and/or "</xyz>".

Another is that you are attempting to do a single match on the whole
string (by using exactMatch()). I am not aware of a method with
QRegExp (or regexes in general) that enables an arbitrary number of
captures to be made. Therefore you need to iterate yourself. Something
like this.

#include <QDebug>
#include <QRegExp>

int main()
{
    QString str = "<xyz>A</xyz>\n"
                        "<xyz>B</xyz>\n"
                        "<xyz>C</xyz>\n";

    QRegExp exp;
    exp.setPattern("<xyz>([^<]*)</xyz>");
    int index = exp.indexIn(str);

    while (index >=0) {
        index += exp.matchedLength();
        qDebug()<<exp.cap(1);
        index = exp.indexIn(str, index);
    }
    return 0;
}

HTH,

Stephen Jackson




More information about the Qt-interest-old mailing list