【问题标题】:Taking every character literally in RegEx在 RegEx 中逐字逐句地理解每个字符
【发布时间】:2016-04-08 08:18:13
【问题描述】:

使用std::regex 我想创建一个函数,例如,一个字符串 并使用该字符串创建一个正则表达式,但字符串的每个字符都匹配字面意思。

例如,假设s("[ds-aa]");我想使用该字符串创建一个正则表达式,但实际上是为了使正则表达式匹配"\[ds\-aa\]"

【问题讨论】:

  • 听起来像你想要的std::string::find
  • 可能使用十六进制表示。 (\xhh)
  • 你的意思是你想要一个 '("[" + someString + "]")' 中的正则表达式,以便它基于字符串变量匹配?
  • 除了看起来你真的需要一个直接的 find 而不是 regex 到底是什么问题?
  • 看来 OP 想要一个引用函数,以便可以构建一个正则表达式,例如 quote(a) + ".*" + quote(b) 以准确地找到 a 然后任何东西然后准确地 b

标签: c++ regex


【解决方案1】:

假设您使用的是std::regex,以及默认的 ECMA 正则表达式风格,您只需要转义

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

所以,你可以使用

#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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-21
    • 1970-01-01
    • 1970-01-01
    • 2013-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-19
    相关资源
    最近更新 更多