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

前端 未结 9 841
情话喂你
情话喂你 2021-02-08 13:15

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 charac

9条回答
  •  遥遥无期
    2021-02-08 13:36

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

提交回复
热议问题