正则表达式

Polyglot_g 2011-10-31 10:13:22
#include<stdio.h>
#include<regex.h>
#define nmatch 5
char *string="Tabs are 8 characters, and thus characters.\n";
int main()
{
regex_t preg;
char *regex="char";
regmatch_t pmatch[nmatch];
unsigned int i,len;
bzero(&preg,sizeof(regex_t));
if(regcomp(&preg,regex,REG_EXTENDED)==0)
{
if(regexec(&preg,string,nmatch,pmatch,0)==0)
{
for(i=0;i<nmatch;i++)
{
if(pmatch[i].rm_so!=-1)
printf("%s\n",string+pmatch[i].rm_so);

}



}




}

return 0;
}


为什么只输出
characters, and thus characters.

我想因该输出
characters, and thus characters.
characters.

请明白人给讲讲,
...全文
127 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
jiang20060606 2011-11-04
  • 打赏
  • 举报
回复

匹配模式1:char *regex="(char)"; //无匹配数量词,最大限度匹配
匹配模式2:char *regex="(char).*(char)"; //.*任意数量匹配,匹配限度可变


5楼LZ的建议相当棒! 我只补充一下匹配规则~~
柯本 2011-11-03
  • 打赏
  • 举报
回复
regexec只能匹配一次,它的pmatch[i]的下标是子匹配用的
要实现你的功能,可用以下程序

#include<stdio.h>
#include<regex.h>
#define nmatch 5
char *string="Tabs are 8 characters, and thus characters.\n";
int main()
{
regex_t preg;
char *regex="(char).+(char)"; //匹配2个char
regmatch_t pmatch[nmatch];
unsigned int i,len;
bzero(&preg,sizeof(regex_t));
if(regcomp(&preg,regex,REG_EXTENDED)==0)
{
if(regexec(&preg,string,nmatch,pmatch,0)==0)
{
for(i=1;i<nmatch;i++) //i=0是全部结果,i=1开始是子匹配的值
{
if(pmatch[i].rm_so!=-1)
printf("%s\n",string+pmatch[i].rm_so);
}
}
}
return 0;
}




机智的呆呆 2011-11-03
  • 打赏
  • 举报
回复
Polyglot_g 2011-11-03
  • 打赏
  • 举报
回复
不知道就别说话
sduxiaoxiang 2011-11-01
  • 打赏
  • 举报
回复
看看库的用法吧
C++正则表达式库不多啊
示申○言舌 2011-10-31
  • 打赏
  • 举报
回复
用的嘛正则库?看看这个库的表达式语法。

69,379

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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