0

I want to clean up QString data to have the following:

input

[[normal]], here's [[double phrased|brackets]]

output

normal, here's double phrased

Just picking the first element in each sub-brackets is fine. I am not sure what the most optimal way to do this?

Also, I am using Qt 4, so this would need to be done by QRegExp.

László Papp
  • 51,870
  • 39
  • 111
  • 135
y2k
  • 65,388
  • 27
  • 61
  • 86

1 Answers1

1

main.cpp

#include <QString>
#include <QDebug>
#include <QRegExp>

int main()
{
    QRegExp rx("\\[{2}([^\\]\\|]+)(\\|[^\\]\\|]+)*\\]{2}");
    QString mystr = "[[normal]], here's [[double phrased|brackets]]";

    for (int pos = 0; (pos = rx.indexIn(mystr, pos)) != -1; pos += rx.matchedLength())
        mystr.replace(pos, rx.matchedLength(), rx.cap(1));

    qDebug() << mystr;

    return 0;
}

Compilation

You may need a slightly different command, but this is here just for reference so that you can adjust for your environment:

g++ -I/usr/include/qt4/QtCore -I/usr/include/qt4 -fPIC -lQtCore main.cpp && ./a.out

Output

"normal, here's double phrased"

Note that, with Qt 5, you should probably converge on to QRegularExpression later.

Also, this is a nice example of why it is good to avoid regex in certain scenarios. Writing a replace functionality here would have taken us less time, and the end result would be more readable, and hence maintainable.

Thanks for lancif for the original inspiration.

László Papp
  • 51,870
  • 39
  • 111
  • 135