How to filter characters from a string using C ++ / Boost

This seems like such a basic question, so I apologize if he was already answered somewhere (my searches did not display anything).

I just want to filter a string object so that it contains only alphanumeric and white space characters.

Here is what I tried:

#include "boost/algorithm/string/erase.hpp"
#include "boost/algorithm/string/classification.hpp"

std::wstring oldStr = "Bla=bla =&*\nSampleSampleSample ";
std::wstring newStr = boost::erase_all_copy(oldStr, !(boost::is_alnum() || 
                                                      boost::is_space()));

But the compiler is not at all happy with this - it seems that I can only put a string in the second argument erase_all_copy, and not this stuff is_alnum().

Is there some obvious solution that I'm missing here?

+3
source share
2 answers

Using std algorithms and Boost.Bind:

std::wstring s = ...
std::wstring new_s;
std::locale loc;
std::remove_copy_if(s.begin(), s.end(), std::back_inserter(new_s), 
    !(boost::bind(&std::isalnum<wchar_t>, _1, loc)||
      boost::bind(&std::isspace<wchar_t>, _1, loc)
));
+1
source

, boost, , , erase_all_regex_copy() erase_all_copy()? , , . , , , "[^ a-zA-Z0-9] +".

, :

#include "boost/regex.hpp"
#include "boost/algorithm/string/regex.hpp"

std::wstring oldStr = "Bla=bla =&*\nSampleSampleSample ";
std::wstring newStr = boost::erase_all_regex_copy(oldStr, boost::regex("[^a-zA-Z0-9 ]+"));
+1

Source: https://habr.com/ru/post/1753755/


All Articles