3

我在 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)在向量中保存多个名称的最佳方法是什么?

提前致谢

康拉德

4

4 回答 4

4

我认为这可以解决问题:

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)]
     ))
于 2008-12-13T22:18:11.890 回答
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 测试)。

于 2010-12-17T15:01:10.417 回答
0

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

string s = "na me has this and that.\n";
myVector . push_back( s.substr( 0, s.find( "has this and that" ) ) );
于 2008-12-13T21:10:27.923 回答
0

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

qi::lit("has this and that")
于 2011-03-02T03:17:02.673 回答