与boost正则表达式库的递归匹配

recursive match with boost regex library

我是 boost 的新手,正在尝试从下面的字符串中的字段构造一个向量(它将是保持方向(Y/NO)和计数的对象的向量),但是这个字符串长度是任意的,有人可以建议我如何将确切的字符串与 boost::regex 匹配并存储它吗?

std::string str = "Y-10,NO-3,NO-4,Y-100"

编辑: 这是我所做的,但不确定这是否是最佳的?

boost::regex expr{"((Y|NO)-\d+)"};
boost::regex_token_iterator<std::string::iterator> it{pattern.begin(), pattern.end(), expr, 1};
boost::regex_token_iterator<std::string::iterator> end;
while (it != end) {
   std::string pat = *it;
   boost::regex sub_expr {"(Y|NO)-(\d+)"};
   boost::smatch match;
   if (boost::regex_search(pat, match, sub_expr)) {
      ...
      ...     
   }
}

我会在这里使用精神:

Live On Coliru

#include <boost/fusion/adapted/std_pair.hpp>
#include <boost/spirit/include/qi.hpp>
namespace qi = boost::spirit::qi;

enum class YNO { NO, Y };

struct YNoToken : qi::symbols<char, YNO> {
    YNoToken() { add("Y", YNO::Y)("NO", YNO::NO); }
} static YNo;

int main() {
    std::string const str = "Y-10,NO-3,NO-4,Y-100";
    auto f = str.begin(), l = str.end();

    std::vector<std::pair<YNO, int> > v;

    bool ok = qi::parse(f, l, (YNo >> '-' >> qi::int_) % ',', v);
    if (ok) {
        std::cout << "Parse success: \n";
        for (auto pair : v)
            std::cout << (pair.first==YNO::Y? "Y":"NO") << "\t" << pair.second << "\n";
    }
    else
        std::cout << "Parse failed\n";

    if (f!=l)
        std::cout << "Remaining unparsed: '" << std::string(f,l) << "'\n";
}

版画

Parse success: 
Y   10
NO  3
NO  4
Y   100

您可以使用正则表达式获得类似的结果,但您需要手动检查和转换子匹配项。