您的位置:首页 > 运维架构 > Linux

在linux下,如何在C语言中使用正则表达式

2016-02-23 09:36 489 查看
使用POSIX函数库中的Regex系列函数来说明在Linux c下如何使用正则表达式

#include <stdio.h>

#include <sys/types.h>

#include <regex.h>

#include <stdlib.h>

#include <string.h>

#define ERRBUF 128

static char * substr(const char * str, unsigned start, unsigned end);

int main(int argc, char *argv[])

{

regex_t myreg;

char err[ERRBUF];

int resulta,resultb;

regmatch_t match[4];

size_t nmatch = 4;

char pattern[] = "[0-9]{3}";

resulta = regcomp(&myreg, pattern, REG_EXTENDED | REG_NEWLINE);

if(resulta != 0)

{

fprintf(stderr, "pattern compiled error\n");

regerror(resulta, &myreg, err, sizeof(err));

regfree(&myreg);

exit(1);

}

char mystring[] = "192.168.121.112";

resultb = regexec(&myreg, mystring, nmatch, match, 0);

if(resultb != 0)

{

regerror(resultb, &myreg, err, sizeof(err));

regfree(&myreg);

exit(1);

}

int x;

for(x = 0; x < nmatch && match[x].rm_so != -1; x++)

{

printf("%s\n",substr(mystring, match[x].rm_so, match[x].rm_eo));

}

printf("x = %d\n",x);

regfree(&myreg);

return 0;

}

static char * substr(const char * str, unsigned start, unsigned end)

{

unsigned n = end - start;

static char strbuf[256];

memset(strbuf,'\0',sizeof(strbuf));

strncpy(strbuf, str + start ,n);

strbuf
= '\0';

return strbuf;

}

注意:不支持使用 \d 来匹配数字
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: