windows平台下,C++正则表达式不能匹配中文
windows 正则表达式对Unicode的支持不好,首先需要设置系统的本地还环境,然后在需要使用宽字符来处理。测试代码如下
#include<iostream>
#include<regex>
#include<string>
#include <locale.h>
using namespace std;
int main()
{
char * pre = setlocale(LC_ALL, "");
cout << pre << endl;
char *now = setlocale(LC_ALL, "chs");
cout << now << endl;
wchar_t ch[]= L"^[a-zA-Z0-9\u4e00-\u9fa5_]{0,29}$";
wstring parten(ch);
wregex re(parten);
wstring str ;
while ( wcin >> str)
{
if (regex_match(str, re)) cout << "success" << endl;
else cout << "fail" << endl;
}
setlocale(LC_ALL, pre);
char *repre = setlocale(LC_ALL, "");
cout << repre << endl;
return 0;
}

在Windows环境下,C++的正则表达式遇到匹配中文字符时可能会失败,主要原因是Windows的正则表达式对Unicode支持不足。解决办法包括设置系统本地化环境和使用宽字符进行处理。

1776

被折叠的 条评论
为什么被折叠?



