首页 > 解决方案 > 使用正则表达式在 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变量传递。

我可以先将流的内容复制到一个字符串中,然后执行标记化,但这似乎效率低下。

标签: c++regextokenize

解决方案


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)}; }
             );

推荐阅读