我需要根据两个分隔符分割一行:' '
和 ;
。
举例:
input : " abc ; def hij klm "
output: {"abc","def","hij","klm"}
如何修复下面的函数以丢弃第一个空元素?
std::vector<std::string> Split(std::string const& line) {
std::regex seps("[ ;]+");
std::sregex_token_iterator rit(line.begin(), line.end(), seps, -1);
return std::vector<std::string>(rit, std::sregex_token_iterator());
}
// input : " abc ; def hij klm "
// output: {"","abc","def","hij","klm"}
下面是编译的完整示例:
#include <iostream>
#include <string>
#include <vector>
#include <regex>
std::vector<std::string> Split(std::string const& line) {
std::regex seps("[ ;]+");
std::sregex_token_iterator rit(line.begin(), line.end(), seps, -1);
return std::vector<std::string>(rit, std::sregex_token_iterator());
}
int main()
{
std::string line = " abc ; def hij klm ";
std::cout << "input: \"" << line << "\"" << std::endl;
auto collection = Split(line);
std::cout << "output: {";
auto bComma = false;
for (auto oneField : collection)
{
std::cout << (bComma ? "," : "") << "\"" << oneField << "\"";
bComma = true;
}
std::cout << "} " << std::endl;
}
最佳答案
到目前为止,我可以看到除了其他问题中提到的几种可能性。第一种是在构建 vector 时使用 std::remove_copy_if
:
// regex stuff here
std::vector<std::string> tokens;
std::remove_copy_if(rit, std::sregex_token_iterator(),
std::back_inserter(tokens),
[](std::string const &s) { return s.empty(); });
另一种可能性是创建一个对字符进行适当分类的语言环境,然后从那里读取:
struct reader: std::ctype<char> {
reader(): std::ctype<char>(get_table()) {}
static std::ctype_base::mask const* get_table() {
static std::vector<std::ctype_base::mask> rc(table_size, std::ctype_base::mask());
rc[' '] = std::ctype_base::space;
rc[';'] = std::ctype_base::space;
// at a guess, newlines are probably still separators too:
rc['\n'] = std::ctype_base::space;
return &rc[0];
}
};
一旦我们有了这个,我们就告诉流在读取(或写入)流时使用该区域设置:
std::stringstream input(" abc ; def hij klm ");
input.imbue(std::locale(std::locale(), new reader));
然后我们可能想要清理仅在标记之间插入逗号的代码,而不是在每个标记之后插入逗号。还好我写了一些code to handle that fairly neatly some time ago 。使用它,我们可以相当简单地将 token 从上面的输入复制到标准输出:
std::cout << "{ ";
std::copy(std::istream_iterator<std::string>(input), {},
infix_ostream_iterator<std::string>(std::cout, ", "));
std::cout << " }";
结果:“{ abc, def, hij, klm }”,完全符合您的预期/希望——没有任何额外的组装来弥补它一开始就做错了事情。
关于c++ - 使用 std::regex 分割行并丢弃空元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44056590/