【正则表达式1】C++11正则表达式

头文件

#include <regex>

regex_match:整个字符串是否匹配

复制代码
    regex reg1("\\w+day");
    string s1 = "saturday";
    string s2 = "saturday and sunday";
    smatch r1;
    smatch r2;
    cout << boolalpha << regex_match(s1, r1, reg1) << endl;  //true
    cout << boolalpha << regex_match(s2, r2, reg1) << endl;  //false
    cout << "s1匹配结果:" << r1.str() << endl;          //saturday
    cout << "s2匹配结果:" << r2.str() << endl;          //空
    cout << endl;
复制代码

regex_match:只返回第一个匹配结果

复制代码
    smatch rr1;
    smatch rr2;
    cout << boolalpha << regex_search(s1, rr1, reg1) << endl;  //true
    cout << "s1匹配结果:" << rr1.str() << endl;           //saturday
    cout << boolalpha << regex_search(s2, rr2, reg1) << endl;  //true
    cout << "s1匹配结果:" << rr2.str() << endl;           //saturday
    cout << endl;
复制代码

iterator:返回多个匹配结果

类似于指针,调用成员要用"->"

复制代码
    cout << "iterator结果:" << endl;
    sregex_iterator it(s2.begin(), s2.end(), reg1);
    sregex_iterator end;
    for(; it != end; ++it)
    {
        cout << it->str() << endl;
        //cout << *it << endl; 错误
    }

    cout << "token_iterator结果:" << endl;
    sregex_token_iterator tit(s2.begin(), s2.end(), reg1);
    sregex_token_iterator tend;
    for(; tit != tend; ++tit)
    {
        cout << tit->str() << endl;
        cout << *tit << endl;
    }
复制代码

 

子表达式匹配

复制代码
    regex reg2("(\\d{1,3}):(\\d{1,3}):(\\d{1,3}):(\\d{1,3})");
    string ip = "0:11:222:333";
    smatch m; 
    regex_match(ip, m, reg2);
    cout << "输出:str()" << endl;
    cout << m.str() << endl;   //0:11:222:333
    cout << m.str(1) << endl;  //0
    cout << m.str(2) << endl;  //11
    cout << m.str(3) << endl;  //222
    cout << m.str(4) << endl;  //333

    cout << "输出:[i]" << endl; //结果同上
    cout << m[0] << endl;
    cout << m[1] << endl;
    cout << m[2] << endl;
    cout << m[3] << endl;
    cout << m[4] << endl;
复制代码

多个匹配结果

复制代码
    string ip2 = "0:11:222:333 4:55:66:7";
    sregex_iterator ip_it(ip2.begin(), ip2.end(), reg2);
    sregex_iterator ip_end;
    for(; ip_it != ip_end; ++ip_it)
    {
        cout << ip_it->str() << endl;
        cout << ip_it->str(1) << endl;
        cout << ip_it->str(2) << endl;
        cout << ip_it->str(3) << endl;
        cout << ip_it->str(4) << endl;
    }
复制代码

 

总的程序:

  View Code

 

参考:

http://www.cnblogs.com/zhuyp1015/archive/2012/04/08/2438191.html

http://www.cnblogs.com/zhuyp1015/archive/2012/04/08/2438215.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值