c++ - 从字面上理解 RegEx 中的每个字符

标签 c++ regex

使用 std::regex 我想创建一个函数,例如,一个字符串 并使用该字符串创建一个 RegEx,但字符串的每个字符都按字面匹配。

例如,假设 s("[ds-aa]");我想使用该字符串创建一个 RegEx,但从字面上看,这样 RegEx 将匹配 "\[ds\-aa\]"

最佳答案

假设您正在使用 std::regex 和默认的 ECMA regex 风格,您只需要转义

. * + ? ^ $ { } ( ) | [ ] \

所以,你可以使用

#include <regex>
#include <string>
#include <iostream>
using namespace std;

std::string regexEscape(std::string str) {
    return std::regex_replace(str, std::regex(R"([.^$|()[\]{}*+?\\])"), R"(\$&)");
}
int main()
{
    std::cout << "Test escaped pattern: " << regexEscape("[da-d$\\]")  << std::endl; // = > \[da-d\$\\\]
    std::string key = "\\56";
    string input = "John\\56 Fred\\12";
    std::regex rx(R"((\w+))" + regexEscape(key));
    smatch m;
    if (std::regex_search(input, m, rx)) {
        std::cout << "Who has \\56? - " << m[1].str() << std::endl;
    }
}

参见 IDEONE demo

结果:

Test escaped pattern: \[da-d\$\\\]
Who has \56? - John

关于c++ - 从字面上理解 RegEx 中的每个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34595899/

相关文章:

c++ - 在 vb.net 中通过引用传递 const 参数

c++ - 在eclipse中找不到opencv库文件

javascript - 获取正则表达式中这些短语之一之后的所有内容?

regex - 仅使用 R 捕获 IP 地址

regex - SED命令删除空行直到第一次出现句子

c++ - 当无法在 C++ 中打开文件时,优雅地失败的最干净的方法是什么?

c++ - 当我从 main 调用 ctor 时,为什么在范围结束之前调用 dtor? (实验性的)

c++ - 作为类参数的模板对象在编译前给出错误

javascript - "if (!' '.replace(/^/, String))"是做什么的?

java - 不贪婪的正则表达式不起作用