On Fri, Mar 20, 2026 at 8:34 PM John Maddock via Boost <boost@lists.boost.org> wrote:
On 20/03/2026 07:29, Olaf van der Spek via Boost wrote:
In this regex the \n matches \r. How is this defined / controlled? Is there a way to only match \n?
std::string s = "[*] A\rB\n"; s = boost::regex_replace(s, boost::regex(R"(\[\*\](.+?)(\n|$))"), "<li>\\1</li>"); std::println("{}", js_encode(s)); // <li> A</li>\rB\n
\n is a regular expression meaning "Match any newline character", which happens to include \r and a few other things as well. If you want to match a literal '\n' then you need to escape it and the appropriate regular expression string is therefore R"\\n"
Hi John, Did you mean R"(\\n)" ? Or "\\n" ? Now I'm confused, I can't get \r to match at all. ++ g++ test.cpp -std=c++26 ++ ./a.out ['.', '\r', '\n', '.'] ['\n'] ['.', '\r', 'X', '.'] ['.', '\r', '\n', '.'] ['\\', 'n'] ['.', '\r', 'X', '.'] ['.', '\r', '\n', '.'] ['\\', '\n'] ['.', '\r', 'X', '.'] ['.', '\r', '\n', '.'] ['\\', '\\', 'n'] ['.', '\r', '\n', '.'] ['.', '\r', '\n', '.'] ['\\', '\\', '\n'] ['.', '\r', '\n', '.'] #include <boost/regex.hpp> #include <print> #include <span> void test(std::string s, std::string re){ std::string a = boost::regex_replace(s, boost::regex(re), "X"); std::println("{} {:18} {}", std::span(s), std::span(re), std::span(a)); } int main() { std::string s = ".\r\n."; test(s, "\n"); test(s, "\\n"); test(s, "\\\n"); test(s, "\\\\n"); test(s, "\\\\\n"); } -- Olaf