Is there a way to combine these two regex?

Viewed 69

Right now I'm processing the following two regex replacements and I'm combining the substitution like this. Is there a way to process the replacement calling regex_replace one time only?

  std::string test_string = "whatever";
  std::regex reg_num("\\\"([0-9]+\\.{0,1}[0-9]*)\\\"");
  std::regex reg_newline("\n+");
  return std::regex_replace(std::regex_replace(test_string, reg_num, "$1"), reg_newline, "");
1 Answers

You can use

std::string test_string = "\"1\" \"1.50\"\nNew line";
std::regex reg_combined("\"([0-9]+\\.?[0-9]*)\"|\n");
std::cout << std::regex_replace(test_string, reg_combined, "$1");

See the C++ demo.

The $1 backreference is initialized with an empty string if Group 1 did not participate in the match, so it is safe to remove line feeds like this.

Pattern details:

  • " - a " char (note you do not need to escape it)
  • ([0-9]+\.?[0-9]*) - Group 1: one or more digits, an optional . and then zero or more digits (are you sure you do not need [0-9]*\.?[0-9]+?)
  • " - a " char
  • | - or
  • \n - a line feed char.
Related