【发布时间】:2019-08-22 02:38:25
【问题描述】:
目标是: 这个json:
{"secretWord1":"private", "something": "\"secretWord2\":\"privateToo\""}
通过 regex_match 转换成这个:
{"secretWord1":"****", "something": "\"secretWord2\":\"****\""}
我有以下三个正则表达式的代码:
std::regex regex1(R"~((\\\"|")((?:[^\\"]*)(?:secretWord1|secretWord2))\1:\1([^\\"]*)\1)~", std::regex_constants::icase);
std::regex regex2(R"~((\\\")((?:[^\\"]*)(?:secretWord1|secretWord2))\1:\1([^\\"]*)\1)~", std::regex_constants::icase);
std::regex regex3(R"~((")((?:[^\\"]*)(?:secretWord1|secretWord2))\1:\1([^\\"]*)\1)~", std::regex_constants::icase);
std::string replaced = someJsonData;
replaced = std::regex_replace(replaced, regex1, "$1$2$1:$1****$1");
replaced = std::regex_replace(std::regex_replace(replaced, regex2, "$1$2$1:$1****$1"), regex3, "$1$2$1:$1****$1");
我想替换秘密信息并将其隐藏在星星后面。第一个正则表达式在
上失败error_stack: regex_error(error_stack): There was insufficient memory to determine whether the regular expression could match the specified character sequence.
第一个表达式有问题吗?因为其他两个表达式只是相互补充,最终,它完成了与 regex1 相同的工作,但当我运行它们时它们运行良好。
在失败期间我无法提供示例代码,但文件不是那么大(大约 30kB)。当我尝试使用 JSON 生成器时,regex1 显然比我结合 regex2+regex3 时要慢。
【问题讨论】:
-
您是否有理由避免使用 JSON 库? stackoverflow.com/q/3512650/2191572是不是因为你的JSON无效?
-
很遗憾,我无法使用您推荐的库。 json字符串有效。
-
错误,该字符串是无效的 JSON。您可以尝试在jsonlint.com 进行验证。我只能假设这些库都不适合您,因为您的 JSON 无效。
-
对不起,您是对的,我提供的代码无效。我已经修好了。但是我正在测试的真实代码是有效的。
-
感谢您愿意反思我的 cmets。请看我的回答。