Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

QString: replace white space behind "</tr>"



  • I want a HTML indent function in QTextEdit.
    Replace white space:

    s = s.replace(QRegExp("[\\s]+"), "") 
    

    I want something like:

    s = s.replace("</tr>white space", "</tr>\n") 
    


  • @sonichy
    You must to scape the slash caracter \\/ in regular expression. Further you can use \\1 to insert the first captured group (</tr>) on replaced string.

    See an example:

    s.replace(QRegularExpression("(<\\/tr>)\\s"), "\\1\n");
    


  • @KillerSmath Worked out, it is should be like these:

    s = s.replace(QRegExp("[\\s]+(<td>)"), "\\1");   // delete white space before <td>
    s = s.replace(QRegExp("[\\s]+(</td>)"), "\\1");   // delete white space before </td>
    s = s.replace(QRegExp("(</tr>)[\\s]+"), "\\1\n");   // delete white space after </tr>
    


  • @KillerSmath

    s.replace(QRegularExpression("(<\\/tr>)\\s"), "\\1\n");
    

    Your answer is useful to the rest of the world, but for anyone reading this you have erroneously inserted a \\, before /tr, which should be removed.



  • @JonB
    Sorry but i used \\ to escape a backward slash to string because / in means "start or end of a regular expression" and it needs to be escaped.

    Usage Example in regular expression
    Forward slash explanation



  • @KillerSmath
    I've used regular expressions in various languages for hundreds of years, and I've never escaped a /. Nor has / ever meant "start of regular expression" as per your sources! So I'm looking into this mystery (for me) now...!

    I'm lost. This is all to do with "using / as the start of a regular expression". But isn't that JavaScript only? Every example on your references has /pattern/, that's not part of regular expressions. I think that's only because they are for using JS string.replace(/.../) "regular expression literal" syntax, no? Why would that apply to QRegularExpression?



  • Or you could use the new C++ 11 literals:

    R"((</tr>)[\s]+)"
    R"delimiter((</tr>)[\s]+)delimiter"
    

    No idea what they were smoking on the delimeter( version.


  • Lifetime Qt Champion

    Hi,

    @KillerSmath what tools are you using for regular expressions ?

    If you take VI for example, / are used to separate elements when doing a search and replace for example. Same with the sed command. With sed you can change the separation char if you need to use / in an expression.


Log in to reply