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?

7
  • Put all the raw literals in separate string variables and add these together. Commented Aug 10, 2019 at 6: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. Commented Aug 10, 2019 at 6:49
  • @πάνταῥεῖ already did that but not work as expected Commented Aug 10, 2019 at 6:51
  • @MurrayW good point, it did not work as if the raw string is hard coded such as re(R"key") Commented Aug 10, 2019 at 6: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 (minimal reproducible example), Commented Aug 10, 2019 at 6:53

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

@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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.