Short answer: Use $&
as a reference to whole match. In this case the correct format string is:
bstr = std::regex_replace(bstr, re, "|$&");
Long answer: Well, this is a rare case where MSVC is right and gcc and clang are (technically) buggy.
C++ default regex flavour is based on ECMAScript standard. This standard defines $n
and $nn
as backreference to a capture group number n
or nn
, but neither of them allows 0
as valid group number. An invalid substitution should be left as is (i.e. treated like any other plain text).
This is what MSVC is doing. It recognizes that $00
substitution is invalid per standard and treats it as plain text. gcc and clang on the other hand made it work like std::regex_match
and treat group number 0
as the whole match. A reasonable assumption, but technically incorrect by standard.
This can be confirmed also with regex101: |$00
is replaced with just that text, |$&
is replaced with the match.