仅当以给定数量的整数开头时如何解析字符串

How to parse string only if starts with given number of integers

给定输入字符串“12a”或"a123",我希望"false"、“123a”-> true 和结果=="a"、“123ab”-> true 和结果=="ab"等

这是我的尝试:

#include <boost/spirit/include/qi.hpp>
#include <string>
#include <iostream>

int main(int argc, char* argv[])
{
    std::string s(argv[1]) ;
    int n = 3;//can be runtime parameter
    std::string result;
    auto expr = boost::spirit::qi::omit
        [
            boost::spirit::qi::repeat(n)[boost::spirit::qi::int_] 
        ]   
        >> +boost::spirit::qi::char_("A-Za-z");

    bool b = boost::spirit::qi::phrase_parse(s.begin(), s.end(), expr, boost::spirit::qi::space, result);
    std::cout << std::boolalpha << b << '\n';
    if(b)
    {
        std::cout << result << '\n';
    }
}

现在 123a、123ab 等 return 错误。

boost::spirit::qi::int_ 是一个贪婪的解析器,它将在第一次重复时消耗所有三个数字。

相反,您应该定义自己的整数解析器,它只会消耗恰好 1 个数字,如下所示:

boost::spirit::qi::uint_parser<unsigned, 10, 1, 1> uint1_p;

并使用 uint1_p 而不是 boost::spirit::qi::int_

编辑:或者,是的...qi::digit 在这里做同样的事情。