学无先后,达者为师

网站首页 编程语言 正文

c++中文字符匹配,但不匹配中文标点的完美解决方案。

作者:CrazyCosin 更新时间: 2022-05-13 编程语言

一、需求

  1. 命名规则:0-9 a-z 不能反斜杠,长度限制(30)
  2. 1. Project命名规则
  3. 1. 可以包含:
  4. 1. 汉字,
  5. 2. 字母(区分大小写),
  6. 3. "_"(英文下划线),
  7. 4. “-”(英文破折线),
  8. 5. “.”(英文点);
  9. 7. 数字
  10. 2. 长度:30个字符;

二、实现

#include 
#include 
#include 
#include 
#include 
#include 

std::wstring transformString2Wstring(const std::string &s)
{
    setlocale(LC_CTYPE, "en_US.UTF-8");
    const char *_Source = s.c_str();
    size_t len = strlen(_Source) + 1;
    size_t converted = 0;
    wchar_t *wStr = new wchar_t[len];
    mbstowcs_s(&converted, wStr, len, _Source, _TRUNCATE);
    std::wstring result(wStr);
    delete[] wStr;
    return result;
}

int main() {
     std::wstring pattern{L"^[\u4E00-\u9FA5A-Za-z0-9][\u4E00-\u9FA5A-Za-z0-9_\\-\\.]{1,30}$"};
     std::wregex re(pattern);
     std::string test_str = "你啊23zs.-_s";
     bool ret = std::regex_match(transformString2Wstring(test_str), re);
     if (!ret) {
           std::cout << "not match \n"; 
     }
}

原文链接:https://blog.csdn.net/CrazyCosin/article/details/124697691

栏目分类
最近更新