'C++ regex_replace not substituting Latex like expression

Looks like regex_replace is only replacing the left parenthesis. And that too is not without a backslash:

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

using namespace std;

int main(int argc, char* argv[])
{
  string text = "\\left( 0 + 1 \\right)";
  text = regex_replace(text, regex("\\left\\("), "(");
  text = regex_replace(text, regex("\\right\\)"), ")");
  cout << text;
  return 0;
}

The output is:

\( 0 + 1 \right)

The expected output is:

( 0 + 1 )


Solution 1:[1]

You should use raw string literals to avoid issues with escaping special regex metacharacters inside regex patterns. As, in a regex, you need two literal backslashes to match a literal backslash char, in a regular string literal you have to use four backslashes, but just two in a raw string literal. "\\\\" = R"(\\)".

Here, you can use a single call to regex_replace:

text = regex_replace(text, regex(R"(\\(left(?=\()|right(?=\))))"), "");

See the C++ demo:

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

using namespace std;

int main(int argc, char* argv[])
{
  string text = "\\left( 0 + 1 \\right)";
  text = regex_replace(text, regex(R"(\\(left(?=\()|right(?=\))))"), "");
  cout << text;
  return 0;
}
// => ( 0 + 1 )

See the regex demo. Details:

  • \\ - a \ char
  • ( - start of a capturing group:
    • left(?=\() - left that has a ( char immediately on the right
    • | - or
    • right(?=\)) - right that has a ) char immediately on the right
  • )

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Wiktor Stribiżew