C ++ std :: regex混乱

时间:2018-05-15 10:49:56

标签: c++ regex

在研究this question的解决方案时,我提出了以下c ++正则表达式:

#include <regex>
#include <string>
#include <iostream>

std::string remove_password(std::string const& input)
{
    // I think this should work for skipping escaped quotes in the password.
    // It works in javascript, but not in the standard library implementation.
    // anyone have any ideas?
    // (.*password\(("|'))(?:\\\2|[^\2])*?(\2.*)
//    const char prog[] = R"__regex((.*password\(')([^']*)('.*)))__regex";
    const char prog[] = R"__regex((.*password\(("|'))(?:\\\2|[^\2])*?(\2.*))__regex";
    auto reg = std::regex(prog, std::regex_constants::syntax_option_type::ECMAScript);
    std::smatch match;
    std::regex_match(input, match, reg);
    // match[0] is the entire string
    // match[1] is pre-password
    // match[2] is the password
    // match[3] is post-password
    return match[1].str() + "********" + match[3].str();
}

int main()
{
    using namespace std::literals;

    auto test_string = R"__(select * from run_on_hive(server('hdp230m2.labs.teradata.com'),username('vijay'),password('vijay'),dbname('default'),query('analyze table default.test01 compute statistics'));)__";

    std::cout << remove_password(test_string);
}

我想捕获密码,即使它们包含转义报价或双引号。

然而正则表达式不能在clang或gcc中编译。

使用javascript语法时,它在regex101.com中正确编译。

我错了,还是执行不正确?

1 个答案:

答案 0 :(得分:3)

请注意ECMAScript是C ++ std::regex中的默认风格,您不必明确指定它。无论如何,std::regex_constants::syntax_option_type::ECMAScript会导致一个错误,因为编译器在此处需要std::regex_constants值,最简单的解决方法是删除它或使用std::regex(prog, std::regex_constants::ECMAScript)

[^\2]模式导致第二个问题,括号表达式中的意外字符。您不能在括号表达式中使用反向引用,但您可以使用否定前瞻来限制. / [^]模式以匹配除组2所持有的任何内容。

使用

const char prog[] = R"((.*password\((["']))(?:\\\2|(?!\2)[^])*?(\2.*))"; 

请参阅your fixed C++ demo

然而,似乎你可以使用&#34;清洁剂&#34;使用std::regex_replace的方法:

std::string remove_password(std::string const& input)
{
    const char prog[] = R"((.*password\((["']))(?:\\\2|(?!\2)[^])*?(\2.*))";
    auto reg = std::regex(prog);
    return std::regex_replace(input, reg, "$1********$3");
}

another C++ demo$1$3是第1组和第3组值的占位符。