1

I want to filter out ${...} with a QRegExp, such that it retuns a QStringList of all selected elements:

"${NAME}" << "${DAY}" << "${MEH}" << "${MEH}" << "${MEH}"

but somehow it doesn't work:

QString text = "Hello ${NAME} \
        How is your ${DAY} so? \
        Bye, ${MEH} ${MEH}\
        ${MEH}";

// Regex: /(\${.*})/g
QRegExp rx("/(\\${.*})/g");
QStringList list;
int pos = 0;

while ((pos = rx.indexIn(text, pos)) != -1) {
    QString val = rx.cap(1);
    list << val;
    qDebug () << "Val: " << val;
    pos += rx.matchedLength();
}

No output at all? What I am doing wrong?

Update:

QRegularExpression works, but only on a per-line and not per-entry level. Ideas?

QString text = "Hello ${NAME} \
        How is your ${DAY} so? \
        Bye, ${MEH} ${MEH}\
        ${MEH}";

QRegularExpression rx("(\\${.*})");
QRegularExpressionMatchIterator i = rx.globalMatch(text);
while (i.hasNext()) {
    QRegularExpressionMatch match = i.next();
    qDebug() << "Value: " << match.captured(0);
}

Output:

Value: "${NAME} \t\t\tHow is your ${DAY} so? \t\t\tBye, ${MEH} ${MEH}\t\t\t${MEH}"

Nicolas Holthaus
  • 7,763
  • 4
  • 42
  • 97

1 Answers1

1

Change the regex to QRegularExpression rx("(\\${.*?})");

Your first attempt didn't work because QRegExp doesn't support global matching via /.../g, and in general, is not perl-compliant. In Qt5, you're better off using the much-improved QRegularExpression.

Your second attempt didn't work because your regex is too greedy. It's grabbing the opening curly brace { up to the last closing curly brace }.

If you add a question mark to the .* capture, you will turn off the greediness, and in this case it will only capture what you are looking for.

Be careful trying to scale this solution much farther though. In general, Regular expressions are not parsers.

Community
  • 1
  • 1
Nicolas Holthaus
  • 7,763
  • 4
  • 42
  • 97