c++正则表达式

#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:三

 

posted @ 2017-01-25 20:59  zhjh256  阅读(173)  评论(0编辑  收藏  举报