我有一个用C语言编写的程序,它可以将正则表达式应用于字符串。
但是,它仅适用于正则表达式
\\w ('\\' means single '\' in string).
\\w+ \\s+ \\s or [^\\s]+
did not take effect.
似乎,
"^","[","]","+"
未得到该计划的认可。
该程序的运行格式如下:
./program {regular expression}
然后输入一行字符串,程序会将正则表达式应用于字符串并给出结果。
我检查程序并没有发现任何错误。
/* the function get a substring from a string */
static char* substr(const char*str,unsigned start, unsigned end)
{
unsigned n = end - start;
static char stbuf[256];
strncpy(stbuf, str + start, n);
stbuf[n] = 0;
return stbuf;
}
/* the main program */
int main(int argc, char** argv)
{
char * pattern;
int x, z, lno = 0, cflags = 0;
char ebuf[128], lbuf[256];
regex_t reg;
regmatch_t pm[10];
const size_t nmatch = 10;
/* complie regular expression*/
pattern = argv[1];
z = regcomp(®, pattern, cflags);
if (z != 0){
regerror(z, ®, ebuf, sizeof(ebuf));
fprintf(stderr, "%s: pattern '%s' \n",ebuf, pattern);
return 1;
}
/* get the line of input string */
while(fgets(lbuf, sizeof(lbuf), stdin))
{
++lno;
if ((z=strlen(lbuf)) > 0 && lbuf[z-1] == '\n')
lbuf[z - 1] = 0;
/* match input line with regular expression */
z = regexec(®, lbuf, nmatch, pm, 0);
if (z == REG_NOMATCH){printf("not match\n,pattern is %s\n",pattern);
continue;}
else if (z != 0) {
regerror(z, ®, ebuf, sizeof(ebuf));
fprintf(stderr, "%s: regcom('%s')\n", ebuf, lbuf);
return 2;
} printf(" $%d='%s'\n", x, substr(lbuf, pm[x].rm_so, pm[x].rm_eo));};
}
}
/*releasing the compiled regular expresion struct*/
regfree(®);
return 0;
}
/* Deal with output result */
for (x = 0; x < nmatch && pm[x].rm_so != -1; ++ x)
{
if (!x) {printf("%04d: %s\n", lno, lbuf);
printf(" pattern is %s",pattern);
printf(" $%d='%s'\n", x, substr(lbuf, pm[x].rm_so, pm[x].rm_eo));};
}
}
/*releasing the compiled regular expresion struct*/
regfree(®);
return 0;
}