C++ - Split string by regex

前端 未结 4 1226
鱼传尺愫
鱼传尺愫 2020-12-05 13:47

I want to split std::string by regex.

I have found some solutions on Stackoverflow, but most of them are splitting string by single space o

4条回答
  •  失恋的感觉
    2020-12-05 14:51

    std::regex rgx("\\s+");
    std::sregex_token_iterator iter(string_to_split.begin(),
        string_to_split.end(),
        rgx,
        -1);
    std::sregex_token_iterator end;
    for ( ; iter != end; ++iter)
        std::cout << *iter << '\n';
    

    The -1 is the key here: when the iterator is constructed the iterator points at the text that precedes the match and after each increment the iterator points at the text that followed the previous match.

    If you don't have C++11, the same thing should work with TR1 or (possibly with slight modification) with Boost.

提交回复
热议问题