- 论坛徽章:
- 0
|
请问C语言里面有没有类似模式匹配的函数啊?
可以帮我看看为什么会有错误吗?
他说rm_so 和rm_eo不是结构体的成员。
/* regex_test.c
* regular expression test in GNU C
*
* tested on redhat6.1
* gcc regex_test.c -o regex_test
*/
#include "stdio.h"
#include <string.h>;
#include <stdlib.h>;
#include <unistd.h>;
#include <sys/types.h>;
#include <regex.h>;
#define SUBSLEN 10
#define EBUFLEN 128 /* error buffer length */
#define BUFLEN 1024 /* matched buffer length */
int
main (int argc, char **argv)
{
FILE *fp;
size_t len; /* store error message length */
regex_t re; /* store compilned regular expression */
regmatch_t subs[SUBSLEN]; /* store matched string position */
char matched[BUFLEN]; /* store matched strings */
char errbuf[EBUFLEN]; /* store error message */
int err, i;
char string[] = "AAAAabaaababAbAbCdCd123123 11(123){12}";
char pattern[] = "(\\([0-9]+\\))(\\{[0-9]+\\}{1})$";
printf ("String : %s\n", string);
printf ("attern: \"%s\"\n", pattern);
/* compile regular expression */
err = regcomp (&re, pattern, REG_EXTENDED);
if (err)
{
len = regerror (err, &re, errbuf, sizeof (errbuf));
fprintf (stderr, "error: regcomp: %s\n", errbuf);
exit (1);
}
printf ("Total has subexpression: %d\n", re.re_nsub);
/* execute pattern match */
err = regexec (&re, string, (size_t)SUBSLEN, subs, 0);
if (err == REG_NOMATCH)
{
fprintf (stderr, "Sorry, no match ...\n"
regfree (&re);
exit (0);
}
else if (err)
{
len = regerror (err, &re, errbuf, sizeof (errbuf));
fprintf (stderr, "error: regexec: %s\n", errbuf);
exit (1);
}
/* if no REG_NOMATCH and no error, then pattern matched */
printf ("\nOK, has matched ...\n\n"
for (i = 0; i <= re.re_nsub; i++)
{
if (i == 0)
{
printf ("begin: %d, end: %d, ", subs.rm_so, subs.rm_eo);
}
else
{
printf ("subexpression %d begin: %d, end: %d, ",
i, subs.rm_so, subs.rm_eo);
}
len = subs.rm_eo - subs.rm_so;
memcpy (matched, string + subs.rm_so, len);
matched[len] = '\0';
printf ("match: %s\n", matched);
}
regfree(&re);
exit(0);
} |
|