Home > OS >  C regex_replace not substituting Latex like expression
C regex_replace not substituting Latex like expression

Time:02-17

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 )

CodePudding user response:

It seems \\\\ is required instead of \\. And also for round braces, I used [(] and [)].

#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[(]"), "(");
  cout << text << endl;
  text = regex_replace(text, regex("\\\\right[)]"), ")");
  cout << text;
  return 0;
}

https://godbolt.org/z/51fhvxYjT

CodePudding user response:

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
  • )
  • Related