如何有效地检查字符串是否在C++中具有特殊字符?

Pra*_*een 8 c++ string c-strings whitelist

我试图找到是否有更好的方法来检查字符串是否有特殊字符.在我的例子中,除了字母数字和'_'之外的任何东西都被认为是一个特殊字符.目前,我有一个包含特殊字符的字符串,例如std :: string ="!@#$%^&".然后我使用std :: find_first_of()算法来检查字符串中是否存在任何特殊字符.

我想知道如何基于白名单来做到这一点.我想在字符串中指定小写/大写字符,数字和下划线(我不想列出它们.有什么方法可以指定某种类型的ascii范围,如[a-zA-Z0-9_] ).我怎样才能做到这一点?然后我计划使用std :: find_first_not_of().通过这种方式,我可以提到我真正想要的东西并检查相反的情况.

Mar*_*ork 13

尝试:

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

或尝试增强正则表达式:

// 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);   
Run Code Online (Sandbox Code Playgroud)

  • 我知道我可以做到这一点,但我想知道我可以提到的范围,如[az AZ 0-9 _]或ascii值范围等. (2认同)