当输入字符串超出范围时增强正则表达式匹配

问题描述 投票:0回答:1

我制作了以下内容以放入我的字符串实用程序中(主要作为记忆辅助):

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。

c++ boost scope
1个回答
0
投票
我无法重现您有关生命周期管理的确切问题。事实上,我遇到了编译错误。但是,通过查看

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
 的有效性。

© www.soinside.com 2019 - 2024. All rights reserved.