1

How build a regex from a string variable, and interpret that as Raw format.

std::regex re{R"pattern"};

For the above code, is there a way to replace the fixed string "pattern" with a std::string pattern; variable that is either built from compile time or run time.

I tried this but didn't work:

std::string pattern = "key";
std::string pattern = std::string("R(\"") + pattern + ")\"";
std::regex re(pattern); // does not work as if it should when write re(R"key")

Specifically, the if using re(R("key") the result is found as expected. But building using re(pattern) with pattern is exactly the same value ("key"), it did not find the result.


This is probably what I need, but it was for Java, not sure if there is anything similar in C++:

How do you use a variable in a regular expression?

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
artm
  • 17,291
  • 6
  • 38
  • 54
  • Put all the raw literals in separate string variables and add these together. – πάντα ῥεῖ Aug 10 '19 at 06:49
  • It would help to know _how_ it didn't work (didn't give you the result you want, or threw an error?) and an example of the string you are processing so others can help you build an appropriate pattern. – MurrayW Aug 10 '19 at 06:49
  • @πάνταῥεῖ already did that but not work as expected – artm Aug 10 '19 at 06:51
  • @MurrayW good point, it did not work as if the raw string is hard coded such as `re(R"key")` – artm Aug 10 '19 at 06:53
  • 2
    `std::string("R(\"")` isn't a raw string literal. Show us a real example of what you've done, and why it didn't work ([mcve]), – πάντα ῥεῖ Aug 10 '19 at 06:53
  • @πάνταῥεῖ is there anything similar like this in C++ ? https://stackoverflow.com/questions/494035/how-do-you-use-a-variable-in-a-regular-expression – artm Aug 10 '19 at 06:56
  • @artm Please clarify if you need the `"` or `()` escaped in the regex pattern or not. – πάντα ῥεῖ Aug 10 '19 at 07:35

1 Answers1

3
 std::string pattern = std::string("R(\"") + pattern + ")\"";

should be build from raw string literals as follows

 pattern = std::string(R"(\")") + pattern + std::string(R"(\")");

This results in a string value like

\"key\"

See a working live example;


In case you want to have escaped parenthesis, you can write

 pattern = std::string(R"(\(")") + pattern + std::string(R"("\))");

This results in a string value like

\("key"\)

Live example


Side note: You can't define the pattern variable twice. Omit the std::string type in follow up uses.

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
  • 1
    @artm You seem to have some misconceptions about what a _raw string_ is. It's still a string like any other. The difference is that for raw string literals you can omit the escaping of all the special characters like `'\'` and `'"'`within the parenthesis. – πάντα ῥεῖ Aug 10 '19 at 07:27