Maison  >  Questions et réponses  >  le corps du texte

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

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

巴扎黑巴扎黑2714 Il y a quelques jours543

répondre à tous(6)je répondrai

  • 迷茫

    迷茫2017-04-17 11:04:55

    在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}.(.*)"

    répondre
    0
  • 阿神

    阿神2017-04-17 11:04:55

    • 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库东西太多,相当臃肿

    répondre
    0
  • 高洛峰

    高洛峰2017-04-17 11:04:55

    你可以用linux自带的regex库。

    répondre
    0
  • 阿神

    阿神2017-04-17 11:04:55

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

    répondre
    0
  • 伊谢尔伦

    伊谢尔伦2017-04-17 11:04:55

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

    répondre
    0
  • 大家讲道理

    大家讲道理2017-04-17 11:04:55

    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

    répondre
    0
  • Annulerrépondre