c++11中的正则表达式库小结(regex)

c++11中的正则表达式库小结(regex)

正则表达式的帮助文档(.chm)

https://download.csdn.net/download/youzai2017/76494981

正则表达式入门和原理(包含贪婪和非贪婪讲解)

目前为止看到的讲正则最牛的博客

https://blog.csdn.net/lxcnn/category_538256.html

本博客是对C++ Primer 5th 17.3的正则表达式做的总结

正则表达式库主要组件

regex表示有一个正则表达式的类
regex_match将一个字符序列与一个正则表达式匹配
regex_search寻找第一个与正则表达式匹配的子序列
regex_replace使用给定格式替换一个正则表达式
sregex_iterator迭代器适配器,调用regex_search来遍历一个string中所有匹配的字串
smatch容器类,保存在string中搜索的结果
ssub_matchstring中匹配的子表达式的结果

regex_match和regex_search的区别?

都是用来确定一个给定字符序列与一个给定的regex是否匹配;

只有整个输入序列与表达式匹配,regex_match才会返回true;

如果一个序列中一个字串与表达式匹配,regex_search函数返回true;

下面一个简单的用法示例:

#include <iostream>
#include <regex>
#include <string>

int main()
{
    // regex_search基本用法
    std::string pattern = "[^c]ei";
    pattern = "[[:alpha:]]*" + pattern + "[[:alpha:]]";
    std::regex r(pattern);
    std::smatch res1;
    std::string testStr1 = "receipt freind theif receive";
    if(std::regex_search(testStr1, res1, r)){
        std::cout << res1->str() << std::endl;
    }
    /*
    结果:freind
    */
    
    // regex_iterator基本用法    使用的是sregex_iterator
    for(std::sregex_iterator it(testStr1.begin(), testStr2.end(), r), endIt; it != endIt; ++it){
        std::cout << it->str() << std::endl;
    }
    /*
    结果:
    freind
    theif
    */
    
    // regex_match基本用法      使用的是sregex_match
    std::regex r2("^(\\S+)-(\\S+)-(\\d+).exe$");
    std::smatch res2;
    std::string testStr2 = "hello-world-ni-hao-1.5.0-123456789.exe";
    if(std::sregex_match(testStr2, res2, r2)){
        std::cout << res2[0] << std::endl;
        std::cout << res2[1] << std::endl;
        std::cout << res2[2] << std::endl;
        std::cout << res2[3] << std::endl;
    }
    /*
    结果:
    hello-world-ni-hao-1.5.0-123456789.exe
    hello-world-ni-hao
    1.5.0
    123456789
    */
    
}

具体请看17.3书本内容

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值