关于windows平台下,C++正则表达式匹配中文失败的问题

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

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

这里写图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值