Important: Please read the Qt Code of Conduct -

QRegExp replace

  • Suppose * and # stand for 2 any string, how to get and replace [*] and (#) ?

    QString s = "![alt](preview.png)"
    if (s.contains("![*](#)")) {
        s.replace("![*](#)", "<img src=" + # + " alt=" + * + ">");

  • @sonichy

    You might want to check out QRegularExpression which is the newer version for regular expressions. It follows the general, common rules for regular expressions.

    You are using a couple of special characters for regular expressions. This is true for '[', ']', '*', '(' and ')'. You need to check if you can escape those letters with a back slash upfront.

    The best is to use the regular expression example for trials (e.g. for QRegExp ). There you can easily see directly if your regular expression is going to capture what you think.

  • Moderators

    For QRegularExpression with allowed escaping: ![((?:(?<=\\)]|[^\]])+)]\(((?:(?<=\\)\)|[^\)])+)\)

    PS. Test is here:

  • An example for inspiration:

        QString s = "start![alt1](preview1.png)middle![alt2](preview2.png)end";
        qDebug().noquote() << "Before:" << s;
        const QRegularExpression r("!\\[([^[]*)\\]\\(([^(]*)\\)");
        for (QRegularExpressionMatch m = r.match(s); m.hasMatch(); m = r.match(s)) {
            s.replace(m.capturedStart(0), m.capturedLength(0),
                      QString("<img src=\"%1\" alt=\"%2\">").arg(m.captured(2)).arg(m.captured(1)));
        qDebug().noquote() << "After: " << s;

    This outputs:

    Before: start![alt1](preview1.png)middle![alt2](preview2.png)end
    After:  start<img src="preview1.png" alt="alt1">middle<img src="preview2.png" alt="alt2">end


  • @Paul-Colby

    warning: unknown escape sequence: '\ ]'
    QRegularExpression r("![([^[]*)]\\(([^(]*)\\)");

  • Hi @sonichy

    Sorry, the forum software is buggy (actually renders properly in the preview panel, yet breaks the presentation when posted). I've updated the post above so it displays correctly.

    The filter should look like: "!\\[([^[]*)\\]\\(([^(]*)\\)"


  • @Paul-Colby Work fine !
    Should we use


    first, because there is


    to deal with.

Log in to reply