Search code examples
c++qtqstring

C++ Qt QString replace double backslash with one


I have a QString with following content:

"MXTP24\\x00\\x00\\xF4\\xF9\\x80\r\n"

I want it to become:

"MXTP24\x00\x00\xF4\xF9\x80\r\n"

I need to replace the "\x" to "\x" so that I can start parsing the values. But the following code, which I think should do the job is not doing anything as I get the same string before and after:

qDebug() << "BEFORE: " << data;
data = data.replace("\\\\x", "\\x", Qt::CaseSensitivity::CaseInsensitive);
qDebug() << "AFTER: " << data;

Here, no change!

enter image description here

Then I tried like this:

data = data.replace("\\x", "\x", Qt::CaseSensitivity::CaseInsensitive);

Then compiler complaines that \x used with no following hex digits!

any ideas?


Solution

  • First let's look at what this piece of code does:

    data.replace("\\\\x", "\\x", ....
    

    First string becomes \\x in compiled code, and is used as regular expression. In reqular expression, backslash is special, and needs to be escaped with another backslash to mean actual single backslash character, and your regexp does just this. 4 backslashes in C+n string literal regexp means matching single literal backslash in target text. So your reqular expression matches literal 2-character string \x.

    Then you replace it. Replacement isn't a reqular expression, so backslash doesn't need double escaping here, so you end up using literal 2-char replacement string \x, which is same as what you matched, so even if there is a match, nothing changes.


    However, this is not your problem, your problem is how qDebug() prints strings. It prints them escaped. That \" at start of output means just plain double quote, 1 char, in the actual string because double quote is escaped. And those \\ also are single backslash char, because literal backslash is also escaped (because it is the escape char and has special meaning for the next char).

    So it seems you don't need to do any search replace at all, just remove it.

    Try printing the QString in one of these ways to get is shown literally:

    std::cout << data << std::endl;
    
    qDebug() << data.toLatin1().constData();