c++11/搜索精确字符串,转义
c++11/search for exact string, escape
假设您有一个用户提供的字符串。它可以包含任何类型的字符。例子:
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
相关文章:
- 如何用转义符替换字符串中的所有特殊字符
- 如何在C++中将 Python 字符串转换为其转义版本?
- 如何解释C++字符串中的 \u 转义码?
- PostgresSQL - SQL Ready 语句与字符串转义,防止 SQL 注入攻击
- 是否可以在原始字符串文本中插入转义序列?
- 转义std::字符串中的特殊字符
- 使变量字符串忽略转义序列
- 在字符串流的 SSH 命令中转义 bash 脚本中的引号
- 转义 R "()" 在 C++ 中的原始字符串中
- 将转义的 UTF-8 八位字节的字符数组转换为 C++ 的字符串
- 使用 RE2::全局替换的转义字符串
- c++ JsonCpp 解析带有转义引号作为数组的字符串
- 如何检测字符串中的转义
- 将带有转义字符的大字符串转换为字节数组
- 由转义字符组成的字符串文字的大小
- 没有数据库连接的字符串转义
- 以编程方式获取 C++ 中的转义字符串表示形式
- C++转义短语子字符串
- c++的简单JSON字符串转义
- c++编译器什么时候开始考虑在字符串转义中使用两个以上的十六进制数字?