|
atl中检测字符串是否在['0'..'9', 'A'..'Z', 'a'..'z', '_']范围内
在ATL中检测字符串是否仅包含数字、字母(大小写)和下划线,可以使用以下方法实现:
使用CAtlRegExp正则表达式(ATL自带方案):
- #include <atlrx.h>
- bool IsValidChars(LPCTSTR str) {
- CAtlRegExp<CAtlRECharTraits> regex;
- REParseError status = regex.Parse(_T("^[0-9A-Za-z_]+$"));
- if (status != REPARSE_ERROR_OK) return false;
-
- CAtlREMatchContext<CAtlRECharTraits> mc;
- return regex.Match(str, &mc);
- }
复制代码
手动遍历检测(高效直接方案):
- bool IsValidChar(TCHAR ch) {
- return (ch >= '0' && ch <= '9') ||
- (ch >= 'A' && ch <= 'Z') ||
- (ch >= 'a' && ch <= 'z') ||
- (ch == '_');
- }
- bool IsValidString(LPCTSTR str) {
- for (int i = 0; str[i] != '\0'; ++i) {
- if (!IsValidChar(str[i])) return false;
- }
- return true;
- }
复制代码
Windows API扩展方案:
- #include <ctype.h>
- bool IsValidStringAPI(LPCTSTR str) {
- for (int i = 0; str[i] != '\0'; ++i) {
- if (!_istalnum(str[i]) && str[i] != '_')
- return false;
- }
- return true;
- }
复制代码
调用示例:
- if (IsValidString(_T("Test_123"))) {
- AtlMessageBox(GetActiveWindow(), _T("有效字符串"));
- }
复制代码
注意事项:
正则表达式方案需要atlrx.h头文件支持
手动遍历方案性能最优,适合短字符串
如需支持Unicode,请使用_TCHAR系列函数
空字符串会被上述函数判定为有效
|
|