【问题标题】:boost spirit extracting first word and store it in a vector提升精神提取第一个单词并将其存储在向量中
【发布时间】:2008-12-13 16:54:41
【问题描述】:

我在 Boost.Spirit 解析字符串时遇到问题。

字符串看起来像

name1 has this and that.\n 
name 2 has this and that.\n 
na me has this and that.\n 

我必须提取名称。文本“有这个和那个”总是相同的,但名称可以包含空格,因此我不能使用 graph_p。

1) 如何解析这样的字符串?

由于字符串有几行这种格式,我必须将名称存储在一个向量中。

我用过类似的东西

std::string name;
rule<> r = *graph_p[append(name)];

为了保存一个名字,但

2) 在一个向量中保存多个名称的最佳方法是什么?

提前致谢

康拉德

【问题讨论】:

    标签: c++ boost boost-spirit


    【解决方案1】:

    我认为这样可以解决问题:

    vector<string> names;
    string name;
    parse(str,
        *(  
           (*(anychar_p - "has this and that.")) [assign_a(name)]
           >> "has this and that.\n") [push_back_a(names, name)]
         ))
    

    【讨论】:

      【解决方案2】:

      如果您使用较新的 Spirit V2.x(这是自 Boost V1.42 以来的默认设置),这很简单:

      #include <boost/spirit/include/qi.hpp>
      
      namespace qi = boost::spirit::qi;
      
      std::vector<std::string> names;
      std::string input = "name1 has this and that.\n"
                          "name 2 has this and that.\n"
                          "na me has this and that.\n";
      bool result = qi::parse(
          input.begin(), input.end(),
          *(*(qi::char_ - " has this and that.\n") >> " has this and that.\n"),
          names
      );
      

      之后,如果resulttrue,则向量names 将保存所有已解析的名称(使用Boost V1.45 测试)。

      【讨论】:

        【解决方案3】:

        我认为您使用Boost.Spirit 而不是STLstringfind 方法是有原因的?例如:

        string s = "na me has this and that.\n";
        myVector . push_back( s.substr( 0, s.find( "has this and that" ) ) );
        

        【讨论】:

          【解决方案4】:

          要删除“有这个和那个”,请使用:

          qi::lit("has this and that")
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2018-04-05
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2013-09-21
            • 2013-02-15
            相关资源
            最近更新 更多