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

recursive match with boost regex library

本文关键字:正则表达式 boost 递归      更新时间:2023-10-16

我是新手,试图从下面的字符串中构造一个向量(它将是持有方向(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)) {
      ...
      ...     
   }
}

我会在这里使用Spirit:

住在科里鲁

#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 failedn";
    if (f!=l)
        std::cout << "Remaining unparsed: '" << std::string(f,l) << "'n";
}

指纹

Parse success: 
Y   10
NO  3
NO  4
Y   100

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