Qt - How to extract text snippets from QString contained within a certain pattern

253 Views Asked by At

Take this as example

QString("= LINK(aaa) + 2 + LINK(bbb) + LINK(ccc)");

I would like to find all text occurences that are contained within LINK().

In my case it should return aaa, bbb and ccc

1

There are 1 best solutions below

0
Dimitry Ernot On

Use QRegExp for that.

QString s("= LINK(aaa) + 2 + LINK(bbb) + LINK(ccc)");
QRegExp rx("LINK\\((.+)\\)");
rx.setMinimal(true);
int i = rx.indexIn(s);
while(i != -1)
{
    qDebug() << rx.capturedTexts() << rx.cap(1);
    i = rx.indexIn(s, i) + rx.cap(0).length();
}

QRegExp::indexIn will return the position of the first match. Add the length of the captured text allows you to browse the whole string.

In my case, I have to use QRegExp::setMinimal() to make the regex non greedy. If you have only letters or digits, you can change the pattern with womething like QRegExp rx("LINK\\((\\w+)\\)")