[SOLVED] Using a QRegularExpression for replacing a character in special conditions?



  • Hi,

    I have a document with several ",".
    Some of them I would like to replace with a dot.

    This is only the case with the following conditions:
    I have a double point followed by a two number digit and then the comma to replace.
    So it could look from ":00,", ":01,"... to ":99," and only the comma shall be replaced.

    I have looked in the QRegularExpression documentation, but I did not really find out whether I can solve it this way.
    For the replacing itself I would like to use the "replace" from the QString class.

    How can I solve this?

    Thank you very much :-)



  • Hi,

    You can use an expression like: (:\d\d),
    With a replacement as: $1.

    So what it does:

    1. match a :
    2. followed by 2 digits (\d\d)
    3. Create a capture group 1 around 1 and 2 using the ().
    4. Match a ,

    The replacement, replaces all full matches with the result of capture group 1 followed by a dot. The comma in the match will be matched by the search but since it is not in the () it will not be part of the group and will not be in the replace string.

    Note: I have not tested it in Qt, make sure you properly escape the expression. The regular expression example might be able to help with the escaping and some testing.
    I am also assuming the ""-parts in the question are not part of the text

    edit: fixed the \d{2} not showing correctly



  • Thank you really much for the nice explanation :-)
    You gave me the right hints.
    The following code does the job:

    s.replace(QRegularExpression("(:\\d\\d),"),"\\1.");
    

Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.