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

Say you have a string provided by the user. It can contain any 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 entries >>, followed by an input line s1, and then <<. For this, I have the following code:

std::string input; // the input text
std::regex regex{">> " + s1 + " <<"};

if (std::regex_match(input, regex)) {
     // add logic here
}

This works great if it s1does not contain special characters. However, if it s1had some special characters that are recognized by the regex engine, it does not work.

How can I avoid s1being std::regextreated as a literal and therefore not interpreted s1? In other words, the regex should be:

std::regex regex{">> " + ESCAPE(s1) + " <<"};

Is there such a function as ESCAPE()in std?

important . . , s1, .

+4
1

\. - regex.

// matches any characters that need to be escaped in RegEx
std::regex specialChars { R"([-[\]{}()*+?.,\^$|#\s])" };

std::string input = ">> "+ s1 +" <<"; 
std::string sanitized = std::regex_replace( input, specialChars, R"(\$&)" );

// "sanitized" can now safely be used in another expression
+2

Source: https://habr.com/ru/post/1658558/


All Articles