C++中 regex 匹配中文字符一例

本文通过一个具体的 C++ 示例展示了如何使用标准库中的正则表达式功能进行字符串匹配、搜索与替换操作。具体包括:设置本地化环境、定义正则表达式、进行全行匹配、查找匹配项及其位置、替换匹配到的内容等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <iostream>
#include <regex>
#include <tchar.h> //_T
using namespace std;


int main()
{
    /*string s0 = "学正楼";
    cout << s0[0] ;
    cout << s0[1] << endl;
*/

    //wcout.imbue(locale("chs", locale::ctype));  //据说有平台问题
    
//wstring s1 = L"学正楼";
    
//wcout << s1[0];

    std::locale loc("");
    std::wcout.imbue(loc);

    std::wstring text(L"我的IP地址是:109.168.0.1.");
    std::wstring newIP(L"127.0.0.1");
    std::wstring regString(L"(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+)");

    // 表达式选项 - 忽略大小写  
    std::regex_constants::syntax_option_type fl = std::regex_constants::icase;

    // 编译一个正则表达式语句  
    std::wregex regExpress(regString, fl);

    // 保存查找的结果  
    std::wsmatch ms;

    // 判断是否全行匹配  
    if (std::regex_match(text, ms, regExpress))
    {
        std::wcout << L"正则表达式:" << regString << L"匹配:" << text << L"成功." << std::endl;
    }
    else
    {
        std::wcout << L"正则表达式:" << regString << L"匹配:" << text << L"失败." << std::endl;
    }

    // 查找  
    if (std::regex_search(text, ms, regExpress))
    {
        std::wcout << L"正则表达式:" << regString << L"查找:" << text << L"成功." << std::endl;
        for (size_t i = 0; i < ms.size(); ++i)
        {
            std::wcout << L"" << i << L"个结果:\"" << ms.str(i) << L"\" - ";
            std::wcout <<L"起始位置:" << ms.position(i) << L"长度" << ms.length(i) << std::endl;
        }
        std::wcout << std::endl;

        // 替换1  
        text = text.replace(ms[0].first, ms[0].second, newIP);
        std::wcout << L"替换1后的文本:" << text << std::endl;
    }
    else
    {
        std::wcout << L"正则表达式:" << regString << L"查找:" << text << L"失败." << std::endl;
    }

    // 替换2  
    newIP = L"255.255.0.0";
    std::wstring newText = std::regex_replace(text, regExpress, newIP);
    std::wcout << L"替换2后的文本:" << newText << std::endl;

    // 结束  
    std::wcout << L"按回车键结束...";
    std::wcin.get();
    return 0;


    getchar();
    return 0;
}

转载于:https://www.cnblogs.com/likeatree/p/3956883.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值