如何在C ++中有效检查字符串是否具有特殊字符? [英] How can I check if a string has special characters in C++ effectively?

查看:641
本文介绍了如何在C ++中有效检查字符串是否具有特殊字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试查找是否有更好的方法来检查字符串是否包含特殊字符。就我而言,除字母数字和 _以外的任何字符都被视为特殊字符。当前,我有一个包含特殊字符的字符串,例如std :: string =!@#$ %% ^&。然后,我使用std :: find_first_of()算法检查字符串中是否存在任何特殊字符。

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.

我想知道如何根据白名单进行操作。我想在字符串中指定小写/大写字符,数字和下划线(我不想列出它们。有什么方法可以指定诸如[a-zA-Z0-9_]之类的ascii范围)。我该如何实现?然后,我计划使用std :: find_first_not_of()。这样,我可以说出我真正想要的,然后检查相反的地方。

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.

推荐答案

尝试:

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

这篇关于如何在C ++中有效检查字符串是否具有特殊字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆