[英]C++ std::regex confusion
在研究此问题的解决方案时,我想到了以下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中正确编译。
我错了吗,还是实现不正确?
请注意, ECMAScript
是C ++ std::regex
的默认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.*))";
请参阅固定的C ++演示 。
但是,您似乎可以通过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");
}
参见另一个C ++演示 。 $1
和$3
是组1和3值的占位符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.