c++11/搜索精确字符串,转义

c++11/search for exact string, escape

本文关键字:字符串 转义 搜索 c++11      更新时间:2023-10-16

假设您有一个用户提供的字符串。它可以包含任何类型的字符。例子:

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

现在我想在一些文本中搜索>>后面跟着输入字符串s1后面跟着<<的出现。为此,我有以下代码:

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

如果s1不包含任何特殊字符,则可以正常工作。但是,如果s1有一些特殊字符,这些字符可以被regex引擎识别,则无法工作。

我怎么能逃避s1,使std::regex认为它是一个文字,因此不解释s1 ?换句话说,正则表达式应该是:

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

std中是否有类似ESCAPE()的功能?

我简化了我的问题。在我的实际情况中,正则表达式要复杂得多。因为我只是对s1被解释的事实有麻烦,我把这些细节遗漏了。

必须用转义字符串中的所有特殊字符。最直接的方法是在创建表达式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