- 论坛徽章:
- 0
|
使用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[n] = '\0';
return strbuf;
}
只能打印出"192",为什么匹配不了后面的内容呢 |
|