我制作了以下内容以放入我的字符串实用程序中(主要作为记忆辅助):
boost::smatch regexMatch(std::string input, std::string regex)
{
boost::smatch match;
boost::regex_match(input, match, boost::regex(regex));
return match;
}
它不起作用,因为
input
超出了范围并且迭代器无效。如果我将参数声明为 std::string&
,则以下内容不起作用:
boost::smatch match;
{
std::string& input = "foo";
match = regexMatch(input, "f..");
}
match.begin()->str();
我怎样才能让它工作而不用担心范围?
顺便说一句,std 正则表达式不好,至少对于 C++17 来说是这样(在匹配我的正则表达式时它会引发复杂性错误)。我使用的是 Boost 1.67。
documentation,您可以尝试使用 boost::cmatch
而不是
boost:smatch
,并对辅助函数进行一些细微的更改。
boost::cmatch regexMatch(std::string input, std::string regex)
{
boost::cmatch match;
boost::regex_match(input.c_str(), match, boost::regex(regex));
return match;
}
另请记住,boost::regex_match()
返回
bool
,您应该使用它来检查
match
的有效性。