c++ - 如何从字符串变量为正则表达式构建原始字符串

标签 c++ regex c++11

如何从字符串变量构建正则表达式,并将其解释为原始格式。

std::regex re{R"pattern"};

对于上面的代码,有没有办法用编译时构建的std::string pattern;变量替换固定字符串"pattern"或运行时。

我试过了但是没用:

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")

具体来说,如果使用 re(R("key") 会按预期找到结果。但是使用带有模式的 re(pattern) 进行构建是完全相同的value ("key"),没有找到结果。


这可能是我需要的,但它是针对 Java 的,不确定 C++ 中是否有类似的东西:

How do you use a variable in a regular expression?

最佳答案

 std::string pattern = std::string("R(\"") + pattern + ")\"";

应按如下方式从原始字符串文字构建

 pattern = std::string(R"(\")") + pattern + std::string(R"(\")");

这会产生类似

的字符串值
\"key\"

查看工作 live example ;


如果你想转义括号,你可以这样写

 pattern = std::string(R"(\(")") + pattern + std::string(R"("\))");

这会产生类似

的字符串值
\("key"\)

Live example


旁注:您不能将 pattern 变量定义两次。在后续使用中省略 std::string 类型。

关于c++ - 如何从字符串变量为正则表达式构建原始字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57439941/

相关文章:

c++ - 如何加载序列化的 boost::variant?

c++ - 当目标是 Windows 时,gyp 中的“拷贝”不会复制整个文件夹

python - str.replace 带括号的函数

c++ - 在 vs2013 中禁用 c++11 功能

c++ -/usr/bin/ld : unrecognized option '-plugin' error

html - 正则表达式替换多个html属性

python - 如何从文本写入 csv?

c++ - 读取文件

c++ - 如何在 GCC 5 中处理双 ABI?

c++ - 如何使用 `llvm::ilist_iterator<NodeTy>::operator pointer() const` 方法?