samedi 22 octobre 2016

c++11/regex - search for exact string, escape

Say you have a string which is provided by the user. It can contain any kind of character. Examples are:

std::string s1{"hello world");
std::string s1{".*");
std::string s1{"*{}97(}{.}}\\testing___just a --%#$%# literal%$#%^"};
...

Now I want to search in some text for occurrences of >> followed by the input string s1 followed by <<. For this, I have the following code:

std::regex regex{">> " + s1 + " <<"};
if (std::regex_match(... the input text ..., regex)) {
     // add logic here
}

This works fine if s1 did not contain any special characters. However, if s1 had some special characters, which are recognized by the regex engine, it doesn't work.

How can I escape s1 such that std::regex considers it as a literal, and therefore does not interpret s1?

Aucun commentaire:

Enregistrer un commentaire