c++11:正则表达式(re)

本文深入探讨了C++11引入的正则表达式库,讲解了如何使用标准模板库(STL)中的`<regex>`头文件进行模式匹配、替换和分割字符串等操作,同时提供了实例代码帮助理解。

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


//#include <boost/regex.hpp>
//using namespace boost;

#include <regex>
#include <string>
#include <iostream>
using namespace std;


void regex_test()
{
    string pattern("[^c]ei");
    pattern = "[[:alpha:]]*" + pattern + "[[:alpha:]]*";
    //pattern = "[[:alpha:]]*";  //匹配零个多多个任意字母
    regex r(pattern,regex::icase);  //regex::icase标志:在匹配过程中忽略大小写。
    smatch results;  //用来保存搜索结果
    string test_str("receipt frEind theif receive");

    //寻找第一个与正则表达式匹配的子序列,并将结果放入到smatch容器中。
    //如果输入序列中一个子串与表达式匹配,则regex_search函数返回true。
    if (regex_search(test_str, results, r)){
        cout << results.str(0) << endl;
        cout << "before "<<results.prefix().str() << endl;  //m.prefix()函数,表示当前匹配之前的序列
        cout << "after "<<results.suffix().str() << endl;  //suffix()函数,表示当前匹配之后的部分
    }

    //如果整个输入序列与表达式匹配,则regex_match函数返回true
    if (regex_match(test_str, r)){
        cout << "ture" << endl;
    }
    else{
        cout << "false" << endl;
    }

    //regex迭代器:sregex_iterator(b,e,r),来获取所有匹配。
    for (sregex_iterator ite(test_str.begin(), test_str.end(), r), end_ite; ite != end_ite; ++ite){
        cout << ite->str()<< endl;
    }


    //子表达式:模式通常包含一个或多个子表达式,通常用括号表示子表达式
    //子表达式常见用途是验证必须匹配特定格式的数据(如电话号码,IP地址等)

    pattern = "(\\()?(\\d{3})(\\))?([-. ])?(\\d{7})";
    regex re_tell(pattern);
    string tell_str("123-1234567");
    if (regex_match(tell_str, re_tell)){
        cout << "phone matched" << endl;
    }
    else{
        cout << "phone did not match" << endl;
    }

    //string fmt("$2.$5.");
    //cout << regex_replace(tell_str, re_tell, fmt) << endl;

    //ip

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值