c++ - 使用 boost::split 分割带有多个分隔符的字符串

标签 c++ string boost

我有一个想要拆分的字符串,因此我使用 boost::split

但是 boost::is_any_of 接受一个字符串并使用每个字符作为分隔符。

我的分隔符应该是“->”和“:”

“:”可以工作,因为它是单个字符分隔符,但“->”不行(它需要每个字符(“-”和“>”分别作为分隔符)

std::vector<std::string> strs;
boost::split(strs, line, boost::is_any_of(["->:"]));

如何定义多个分隔符,其中一些分隔符超过一个字符?

示例:

"0:c->2"   should give [0,"c",2]

如果其他解决方案更容易解决特定问题,我愿意接受不使用 boost 的其他解决方案

最佳答案

您可以使用Boost.Spirit来解析字符串:

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

namespace qi = boost::spirit::qi;

int main()
{
    std::string str = "0:c->2";
    std::vector< std::string > vec;

    auto it = str.begin(), end = str.end();
    bool res = qi::parse(it, end,
        qi::as_string[ *(qi::char_ - ':' - "->") ] % (qi::lit(':') | qi::lit("->")),
        vec);

    std::cout << "Parsed:";
    for (auto const& s : vec)
        std::cout << " \"" << s << "\"";

    std::cout << std::endl;
    return 0;
}

这里,解析器生成与 *(qi::char_ - ':' - "->") 解析器匹配的字符串列表(读作“任意数量的任意字符,除 ':' 或 "->""),由与 (qi::lit(':') | qi::lit("->")) 解析器匹配的字符串分隔(其中读作“‘:’字符或“->”字符串”)。第一个解析器必须排除分隔符,否则它们将包含在解析的字符串中。 qi::as_string 部分只是将解析的字符转换为 std::string 属性,然后将其附加到 vec 序列中。

关于c++ - 使用 boost::split 分割带有多个分隔符的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53653975/

相关文章:

c++ - 使用 QT 4.7.4 窗口显示带有 libvlc 2.1.0 的视频

python - 在 Python 中将字符串转换为整数

string - PowerShell用日期和时间替换两个字符串之间的文本

c++ - 使用 boost::archive::binary_iarchive 的内存泄漏

c++ - 使用 Boost Polygon 的减法结果不正确

c++ - 链接器错误 - 带有 libboost_thread 的 macOS 上 undefined symbol std::string::c_str() const?

c++ - 在 visual studio 2010 中编译 IDL 文件时无法生成必要的文件

c++ - Boost:错误的模板参数数量

c++ - (long long)x 与 C++ 中的 (long long)floor(x) 相同吗?

Java:子字符串.匹配数字