c++ - 使用正则表达式在 C++ 中标记流
问题描述
我想使用类似于对字符串执行此操作的方式的正则表达式在 C++ 中标记流:
std::vector<std::string> tokenize(const std::string& source, const std::regex& re)
{
auto tokens = std::vector<std::string>(
std::sregex_token_iterator{ begin(source), end(source), re, -1 },
std::sregex_token_iterator{}
);
return tokens;
}
不同之处在于将 anistream
作为source
变量传递。
我可以先将流的内容复制到一个字符串中,然后执行标记化,但这似乎效率低下。
解决方案
transform_reduce(istream_iterator<string>(cin), istream_iterator<string>(),
vector<string>{},
[](auto&& a, auto&& b) {
auto acc = [](auto&& h, auto&& w) { h.emplace_back(w); return move(h); };
if constexpr (is_same_v<decay_t<decltype(a)>, vector<string>>)
return accumulate(istream_iterator<string>(b), istream_iterator<string>(), move(a), acc);
else
return accumulate(istream_iterator<string>(a), istream_iterator<string>(), move(b), acc);
},
[&](auto l) { replace_if(l.begin(), l.end(), is_word_seperators, ' '); return stringstream{move(l)}; }
);
推荐阅读
- java - 在 JFrame 上自动生成新的 JPanel
- r - 将数据格式从 DataTime 更改为通用 r
- javascript - 如何从 UserFrosting 控制器正确返回 .xls Excel 文件并在 Angular 2+ 中处理它?
- javascript - 如何使用相同的按钮打开和关闭我的汉堡菜单?
- ios - UICollectionView 不重新加载数据
- javascript - 使用 JS 或 jQuery 从 DOM 中完全删除元素/标签?
- python - 无法验证 tensorflow 安装 Windown 10
- sql - 计为重复的相似值
- javascript - 如何通过浏览器从 PHP 远程执行 PhantomJS
- node.js - 登录在 Postman 中持续存在,但在使用 Angular 的浏览器中不存在