C++ regex difference between platforms

Viewed 110

I have the following code:

#include <string>
#include <regex>
#include <iostream>

int main()
{
        std::string s;
        s += '\x06';
        s += '\x00';

        std::regex r(std::string(1, '\x06') + '\x00');
        std::smatch sm;
        if (std::regex_search(s, sm, r))
        {
                std::cout << "Success\n";
                return 0;
        }

        std::cout << "Failure\n";
}

On Windows, I get "Success" while on Linux, I get "Failure". I use MSVC 19.28 on Windows and GNU 9.3.0 on Linux. Why is the output different?

1 Answers

According to the C++ ECMAScript regex flavor reference,

The decimal escape \0 is NOT a backreference: it is a character escape that represents the nul character. It cannot be followed by a decimal digit.

So, to match a NULL char, you need to use \0 literal text, a literal \ char and a 0 char. You can define it with a regular string literal as "\\0" or - better - with a raw string literal, R"(\0)".

The following prints "Success":

#include <string>
#include <regex>
#include <iostream>

int main()
{
        std::string s;
        s += '\x06';
        s += '\x00';
        std::regex r(std::string(1, '\x06') + R"(\0)");
        std::smatch sm;
        if (std::regex_search(s, sm, r))
        {
                std::cout << "Success\n";
                return 0;
        }

        std::cout << "Failure\n";
}
Related