Search code examples
c++stringwhitelistc-strings

How can I check if a string has special characters in C++ effectively?


I am trying to find if there is better way to check if the string has special characters. In my case, anything other than alphanumeric and a '_' is considered a special character. Currently, I have a string that contains special characters such as std::string = "!@#$%^&". I then use the std::find_first_of () algorithm to check if any of the special characters are present in the string.

I was wondering how to do it based on whitelisting. I want to specify the lowercase/uppercase characters, numbers and an underscore in a string ( I don't want to list them. Is there any way I can specify the ascii range of some sort like [a-zA-Z0-9_]). How can I achieve this? Then I plan to use the std::find_first_not_of(). In this way I can mention what I actually want and check for the opposite.


Solution

  • Try:

    std::string  x(/*Load*/);
    if (x.find_first_not_of("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890_") != std::string::npos)
    {
        std::cerr << "Error\n";
    }
    

    Or try boost regular expressions:

    // Note: \w matches any word character `alphanumeric plus "_"`
    boost::regex test("\w+", re,boost::regex::perl);
    if (!boost::regex_match(x.begin(), x.end(), test)
    {
        std::cerr << "Error\n";
    }
    
    // The equivalent to \w should be:
    boost::regex test("[A-Za-z0-9_]+", re,boost::regex::perl);