码迷,mamicode.com
首页 > 编程语言 > 详细

c++正则表达式

时间:2017-01-25 21:17:39      阅读:222      评论:0      收藏:0      [点我收藏+]

标签:color   bsp   style   pac   正则表达   pre   data   cout   for   

#include <regex>
using namespace std;

void out(bool b) {
    cout << (b ? "found" : "not found") << endl;
}

int _tmain(int argc, _TCHAR* argv[])
{
    regex reg1("<.*>.*</.*>");
        // 常规匹配
    bool found = regex_match("<tag>test c++ regexp</tag1>",reg1);
    out(found);
    regex reg2("<(.*)>.*</\\1>"); // 就配对解析而言, 一定得失前向引用
    found = regex_match("<tag>test c++ regexp</tag1>",reg2);
    out(found);
}

输出:

out found

found

第二种比较常见的用法是找出所有匹配的串,如下:

    string data="<person>\n"
                "<first>张</first>"
                "<last>三</last>"
                "</person>";
    regex reg3("<(.*)>(.*)</\\1>");
    sregex_iterator pos(data.cbegin(),data.cend(),reg3);
    sregex_iterator end2;
    for(;pos!=end2;++pos) {
        cout << "match:" << pos->str() << endl;
        cout << "  tag:" << pos->str(1) << endl;
        cout << "value:" << pos->str(2) << endl;
    }

输出:

match:<first>张</first>
  tag:first
value:张
match:<last>三</last>
  tag:last
value:三

 

c++正则表达式

标签:color   bsp   style   pac   正则表达   pre   data   cout   for   

原文地址:http://www.cnblogs.com/zhjh256/p/6350061.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!