Nominate our 2022 Qt Champions!

QRegularExpression and QString::replace()

  • Hi,
    I have this QString:

    @name="abc" blabla="xyz"
    name='abc' blabla='uvw'
    name=abc blabla='uvw'

    I want to replace the item abc with something else, let's say with foo.

    Using regular expressions I'm able to catch the three cases (no/single/double quotes), for example:

    @re = ""(abc)"|'(abc)'|(abc)";
    Now I want to replace them with foo, maintaining their syntax.
    But if I try with:

    myString.replace(QRegular[removed]re), "foo");

    it replaces not only the captured text but also the quotes (if any).
    How to avoid that?


  • Moderators

    Maybe I'm missing something, but why not just
    myString.replace("abc", "foo");

  • Because what if abc is contained in another word?

  • Moderators

    Then your regexp won't help either, unless you extend it to consider spaces etc.

    You can capture what's before and after the "abc" with separate groups and use them in replacing string:
    QRegularExpression re("("|'|=|\s)abc("|'|\s)");
    str.replace(re, "\1foo\2")

  • @#include <QRegularExpression>
    #include <QDebug>

    int main(int argc, char *argv[])
    QRegularExpression regex(QStringLiteral("(?<=["'=])abc(?=["' ]|$)"));

    QString first("name=\"abc\"");
    QString second("name='abc'");
    QString third("name=abc");
    QString thirdWithSpace("name=abc ");
    QString noMatch("blabcla");
    QString noMatchThird("name=abcc");
    qDebug() << regex.match(first);
    qDebug() << regex.match(second);
    qDebug() << regex.match(third);
    qDebug() << regex.match(thirdWithSpace);
    qDebug() << regex.match(noMatch);
    qDebug() << regex.match(noMatchThird);
    QString replace("foo");
    qDebug() << first.replace(regex, replace);
    qDebug() << second.replace(regex, replace);
    qDebug() << third.replace(regex, replace);
    qDebug() << thirdWithSpace.replace(regex, replace);
    qDebug() << noMatch.replace(regex, replace);
    qDebug() << noMatchThird.replace(regex, replace);
    return 0;


    Using lookahead and lookbehind I managed to create this.

  • Interesting! Thanks both.

  • [quote]Because what if abc is contained in another word? [/quote]
    @re = "<abc>";@


Log in to reply