正则表达式 - c++标准库中没有关于正则匹配字符串的函数么?
巴扎黑
巴扎黑 2017-04-17 11:02:55
0
6
538

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

巴扎黑
巴扎黑

reply all(6)
迷茫

在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}.(.*)"
阿神
  • C++98里肯定是没有正则库的
  • C++0x有std::regex,目前只有VS2010+支持 GCC(libstd++)不支持
  • PCRE/PCRE++是比较老牌的C/C++正则库,跨平台
  • linux下glibc里有正则库,直接include "regex.h"
  • windows下可以用com调vbscript的IRegExp2正则接口,任何版本windows适用,不需要任何额外依赖,速度也很快
  • boost里也有正则,但是boost库东西太多,相当臃肿
小葫芦

你可以用linux自带的regex库。

阿神

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

伊谢尔伦

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!