提升正则表达式标记生成器和换行符

时间:2011-04-22 15:11:09

标签: c++ regex boost tokenize

我正在尝试在遇到换行符时将文本文件拆分为字符串向量。以前我使用boost tokenizer与其他分隔符一起使用,但是当我使用换行符'\ n'时它会在运行时抛出异常:

terminate called after throwing an instance of 'boost::escaped_list_error'
  what():  unknown escape sequence
Aborted

以下是代码:

std::vector<std::string> parse_lines(const std::string& input_str){
    using namespace boost;
    std::vector<std::string> parsed;
    tokenizer<escaped_list_separator<char> > tk(input_str, escaped_list_separator<char>('\n'));
    for (tokenizer<escaped_list_separator<char> >::iterator i(tk3.begin());
                i != tk.end(); ++i) 
    {
       parsed.push_back(*i);
    }
    return parsed;
}

非常感谢任何建议!

3 个答案:

答案 0 :(得分:4)

escaped_list_separator的构造函数需要转义符,然后是分隔符,然后是引号字符。通过使用换行符作为转义字符,它将输入中每行中的第一个字符视为转义序列的一部分。试试这个。

escaped_list_separator<char>('\\', '\n')

http://www.boost.org/doc/libs/1_46_1/libs/tokenizer/escaped_list_separator.htm

答案 1 :(得分:3)

鉴于你想要的分隔符已经被标准库直接支持,我想我根本不会使用正则表达式,并使用标准库中已经存在的东西:

std::vector<std::string> parse_lines(std::string const &input_string) { 
    std::istringstream buffer(input_string);
    std::vector<std::string> ret;
    std::string line;

    while (std::getline(buffer, line))
        ret.push_back(line);
    return ret;
}

一旦你通过将字符串视为流并从那里读取行来处理问题,你就可以从中获得有关如何去的详细信息。仅举几个示例,您可能希望使用@UncleBens和我发布的行代理和/或LineInputIterator类来响应previous question

答案 2 :(得分:1)

这可能会更好。

boost::char_separator<char> sep("\n");
boost::tokenizer<boost::char_separator<char>> tokens(text, sep);

编辑:或者,您可以使用std::find并制作自己的分割器循环。

相关问题