regex C++正则表达式简单使用

/*
 * 正则表达式是在运行时而非编译时编译的
 * 构造一个regex或对一个已有的regex赋新值可能非常耗时
 * 我们应该尽量避免不必要的regex
 */

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

using namespace std;

int main2()
{
    //搜索关键字为ei且前面不是紧接c
    string pattern("[^c]ei");
    pattern = "[[:alpha:]]*"+pattern+"[[:alpha:]]*";
    regex r(pattern);
    //smatch 容器类,保存string中搜索的结果
    smatch result;
    string test_str = "recepit freind theif receive";
//    if(regex_search(test_str,result,r)){  //regex_search找到一个就停止了
//        cout<<result.str()<<endl;
//    }
    int i=0;
    while (std::regex_search (test_str,result,r)) {
        for (auto x:result)
            std::cout << i++ << " :" << x << " "<<std::endl;
        test_str = result.suffix().str();//当前结果的后续字段
        test_str.erase(0,test_str.find_first_not_of(" "));
        cout<<test_str<<endl;
    }
    return 0;
}
int main1 ()
{
    std::string s ("there is a needle in this haystack");
    std::smatch m;
    std::regex e ("needle");

    std::cout << "searching for needle in [" << s << "]\n";
    std::regex_search ( s, m, e );

    if (m.ready()) {
    std::cout << m[0] << " found!\n";
    std::cout << "prefix: [" << m.prefix() << "]\n";
    std::cout << "suffix: [" << m.suffix() << "]\n";
    }

    return 0;
}
int main(){
    std::string s ("there is a needle in this haystack");
    //match参数类型与输入序列不匹配,在下面的regex_search使用了一个char*
    std::cmatch m;
    std::regex e ("needle");

    std::cout << "searching for needle in [" << s << "]\n";
    std::regex_search ( "there is a needle in this haystack", m, e );

    cout<<m[0]<<endl;

    return 0;
}
调整main的结构(去掉main后面的数字把其他的加上数字让它只有一个main有效)调出的结果依次是:



  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值