Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/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.


  • Qt Champions 2017

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

    PS. Test is here: https://regex101.com/r/mvkzHU/1



  • 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
    

    Cheers.



  • @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: "!\\[([^[]*)\\]\\(([^(]*)\\)"

    Cheers.



  • @Paul-Colby Work fine !
    Should we use

    if(s.contains("![*](#)"))
    

    first, because there is

    if(s.contains("[*](#)"))
    

    to deal with.


Log in to reply