首页 > c++标准库中没有关于正则匹配字符串的函数么?

c++标准库中没有关于正则匹配字符串的函数么?

我想实现的是查找满足正则条件的字符串,google了一下,发现都是用的boost中的函数,难道标准库中没有相关函数么?


在Linux下你可以很方便的使用regex.h提供的库。我先贴一段代码展示一下RE在C语言里是怎么用的
,比较粗略点

#include<stdio.h>
#include<sys/types.h>
#include<regex.h>
#include<memory.h>
#include<stdlib.h>

int main()
{
 
    char *bematch = "hhhericchd@gmail.com";
    char *pattern = "h{3,10}(.*)@.{5}.(.*)";
    char errbuf[1024];
    char match[100];
    
    regex_t reg;
    int err,nm = 10;
    regmatch_t pmatch[nm];
 
    if(regcomp(&reg,pattern,REG_EXTENDED) < 0){
        regerror(err,&reg,errbuf,sizeof(errbuf));
        printf("err:%s\n",errbuf);
    }
 
    err = regexec(&reg,bematch,nm,pmatch,0);
    if(err == REG_NOMATCH){
        printf("no match\n");
        exit(-1);
    }else if(err){
        regerror(err,&reg,errbuf,sizeof(errbuf));
        printf("err:%s\n",errbuf);
        exit(-1);
    }
 
    for(int i=0;i<10 && pmatch[i].rm_so!=-1;i++){
        int len = pmatch[i].rm_eo-pmatch[i].rm_so;
        if(len){
            memset(match,'\0',sizeof(match));
            memcpy(match,bematch+pmatch[i].rm_so,len);
            printf("%s\n",match);
        }
    }
  
    return 0;
}

我打算看看一个邮件地址是否匹配我所提供的pattern。这个邮件地址是
hhhericchd@gmail.com patern为

"h{3,10}(.*)@.{5}.(.*)"

貌似只有一些第三方的,微软有一个,boost的应该更通用一点吧.


你可以用linux自带的regex库。



pcre 是个著名的正则库. php就在用它


c++11的<regex>
Eg:

#include <regex>
#include <iostream>
using namespace std;
//匹配手机号码
int main() {
    regex reg;
    regex_constants::syntax_option_type fl = regex_constants::icase;
    reg.assign("\\b1[35][0-9]\\d{8}|147\\d{8}|1[8][01236789]\\d{8}\\b", fl);
    bool found1 = regex_match("13536921192", reg);
    cout<<found1<<endl;
}

参见:http://www.codeceo.com/article/cpp11-regex-code.html

【热门文章】
【热门文章】