• c++ 正则匹配


    语法:

    std::regex         //pattern
    std::regex_match   //对string用pattern进行匹配, 从头匹配到尾
    std::match_results //捕获匹配的内容
    

    代码

    #include <iostream>
    #include <regex>
    
    int main()
    {
        using std::string;
        using std::cout;
        using std::endl;
        using std::regex;
        using std::regex_match;
        using std::match_results;
    
        string s0 = "012-3456-789";
    
        //设置patten, R"()"表示内部是正则字符串, \就表示\, 不需要用\\转义
        //    注意, R"()"中, 引号最外围的括号是语法的一部分, 不是捕获括号.
        regex regex_number(R"((\d+)-(\d+)-(\d+))");
    
        //声明match_results, 用于捕获匹配内容
        match_results<string::const_iterator> match_results_number;
    
        //进行匹配, 注意regex_match会匹配整个字段, 从头到尾
        bool b_match_number = regex_match(s0, match_results_number, regex_number);
    
        //查看匹配结果
        if (b_match_number)
        {
            cout << "match:" << endl;
            cout << "    0: " << match_results_number[0] << endl; //整个字串: 012-3456-789
            cout << "    1: " << match_results_number[1] << endl; //第一个括号: 123
            cout << "    2: " << match_results_number[2] << endl; //第二个括号: 3456
            cout << "    3: " << match_results_number[3] << endl; //第三个括号: 789
        } else
        {
            cout << "not match" << endl;
        }
    
        //遍历捕获的内容
        for(auto iter=match_results_number.begin(); iter!=match_results_number.end(); iter++)
        {
            //使用iter.str()可以得到对应字符串.
            cout << "length=" << iter->length() << ", str=" << iter->str() << endl;
        }
        //输出:
        //length=12, str=012-3456-789
        //length=3, str=012
        //length=4, str=3456
        //length=3, str=789
    }
    
  • 相关阅读:
    Log4Net使用指南
    Log4net 写文件日志与数据库日志
    JSON-Schema 最科学的表单验证模式
    番茄时间工作法
    css 温故而知新 1px的问题
    $.ajax 温故而知新坑
    H5中滚动卡顿的问题
    横向思维
    Wd 西部数据
    使用AlloyLever来搞定开发调试发布,错误监控上报,用户问题定位
  • 原文地址:https://www.cnblogs.com/gaiqingfeng/p/16323771.html
Copyright © 2020-2023  润新知