C++ :: Boost :: Regex迭代子匹配

Mic*_*ael 6 c++ regex boost

我正在使用带有Boost Regex/Xpressive的命名捕获组.

我想迭代所有子匹配,并获得每个子匹配的值和KEY(即什么["type"]).

sregex pattern = sregex::compile(  "(?P<type>href|src)=\"(?P<url>[^\"]+)\""    );

sregex_iterator cur( web_buffer.begin(), web_buffer.end(), pattern );
sregex_iterator end;

for( ; cur != end; ++cur ){
    smatch const &what = *cur;

    //I know how to access using a string key: what["type"]
    std::cout << what[0] << " [" << what["type"] << "] [" << what["url"] <<"]"<< std::endl;

    /*I know how to iterate, using an integer key, but I would
      like to also get the original KEY into a variable, i.e.
      in case of what[1], get both the value AND "type"
    */
    for(i=0; i<what.size(); i++){
        std::cout << "{} = [" << what[i] << "]" << std::endl;
    }

    std::cout << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

boa*_*der 2

看了一个多小时后,我很有把握地说:“这是不可能的,队长”。即使在 boost 代码中,它们在查找时也会迭代私有的named_marks_向量。只是没有设置允许这样做。我想说最好的选择是迭代您认为应该存在的那些,并捕获那些未找到的异常。

const_reference at_(char_type const *name) const
{
    for(std::size_t i = 0; i < this->named_marks_.size(); ++i)
    {
        if(this->named_marks_[i].name_ == name)
        {
            return this->sub_matches_[ this->named_marks_[i].mark_nbr_ ];
        }
    }
    BOOST_THROW_EXCEPTION(
        regex_error(regex_constants::error_badmark, "invalid named back-reference")
    );
    // Should never execute, but if it does, this returns
    // a "null" sub_match.
    return this->sub_matches_[this->sub_matches_.size()];
}
Run Code Online (Sandbox Code Playgroud)