特急!!!如何使用regexp来进行正则表达式的匹配?

escapestar 2000-06-17 05:27:00
加精
如何使用regexp来进行正则表达式的匹配?
下面这个程序有何不妥,请各位打下指正:
#define INIT register char *sp=instring;
#define GETC() (*sp++)
#define PEEKC() (*sp)
#define UNGETC(c) (--sp)
#define RETURN(c) return;
#define ERROR(c) regerr()
#include <stdio.h>
#include <regexp.h>
main()
{
char expbuf[10];
char linebuf[80];
strcpy(expbuf,"^[0-9]*$");
compile((char *)0,expbuf,&expbuf[sizeof(expbuf)],'\0');
for (;;)
{
printf("please input a string:\n");
scanf("%s\n",linebuf);
if (step(linebuf,expbuf))
{
printf("success!\n");
}
else
printf("failed!\n");
}
}

编译时提示regerr未定义,不知何故?希望各位大虾能以例程解答
请发email至bone_dragon@21cn.com,多谢!
...全文
148 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
hem 2001-05-18
  • 打赏
  • 举报
回复
参考
hu_zy 2000-12-31
  • 打赏
  • 举报
回复
真想知道这个函数是怎么实现的,要是知道请不吝赐教。
开始我不知道存在这个函数,还打算写一个出来呢。
可是想来想去也没想到一个比较好的,只能通过最基本的从
上到下分析法,需要回溯,实在是麻烦的要紧。
solar 2000-06-18
  • 打赏
  • 举报
回复
pmatch用来保存匹配到的子串下标.
pmatch 是一个元素类型为regmatch_t的数组,在上例中有16个元素:

typedef struct
{
regoff_t rm_so;
regoff_t rm_eo;
} regmatch_t;

其中 rm_so 是子串首元素的下标(-1表示结束),rm_eo是子串末元素的下标加1;
pmatch[0]保存整个正则表达式的下标;
pmatch[1]保存正则表达式中第一个用"("和")"括起的部分的下标;
pmatch[2]...第二个...,

for example:
------------------------------
/* regtest2.c */

#include <stdio.h>
#include <regex.h>

#define MAX_MATCH 16

main()
{
int i;
regex_t re;
char *expbuf="(hello)[0-9]*(world)";
char linebuf[80]="regexp_test hello123world good";
regmatch_t pmatch[MAX_MATCH];

printf("regular expression: %s\nInput string: %s\n",expbuf,linebuf);

regcomp(&re,expbuf,REG_EXTENDED);
if(0 == regexec(&re, linebuf, MAX_MATCH,pmatch,0)){
for(i=0;i<MAX_MATCH,pmatch[i].rm_so != -1;i++)
printf("start=%d, end=%d\n",pmatch[i].rm_so,pmatch[i].rm_eo);
}
else
printf("failed!\n");
regfree(&re);
}
------------------------------
bash-2.04# ./regtest2
regular expression: (hello)[0-9]*(world)
Input string: regexp_test hello123world good
start=12, end=25
start=12, end=17
start=20, end=25

escapestar 2000-06-18
  • 打赏
  • 举报
回复
多谢指点,感激不尽,还有点小问题
能解释一下pmatch的作用么?
solar 2000-06-18
  • 打赏
  • 举报
回复
maybe this will help:
-----------------------------------
/*
**regtest.c: 已在linux(egcs) & solaris(gcc-2.95.2) 下调试通过
*/
#include <stdio.h>
#include <regex.h>
main()
{
regex_t re;
char *expbuf="^[0-9]*$";
char linebuf[80];
regmatch_t pmatch[16];

regcomp(&re,expbuf,0);
for (;;){
printf("please input a string:\n");
scanf("%s",linebuf);
if(0 == regexec(&re, linebuf, 16,pmatch,0))
printf("success!\n");
else
printf("failed!\n");
}
}

19,612

社区成员

发帖
与我相关
我的任务
社区描述
系统使用、管理、维护问题。可以是Ubuntu, Fedora, Unix等等
社区管理员
  • 系统维护与使用区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧