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 @   zhjh256  阅读(177)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示