Chinaunix

标题: 如何在C语言中巧用正则表达式 [打印本页]

作者: fwizard    时间: 2004-04-13 22:22
标题: 如何在C语言中巧用正则表达式
看到大家讨论这方面的东西,作点贡献聊表各位高手对这个版快的无私奉献

如果用户熟悉Linux下的sed、awk、grep或vi,那么对正则表达式这一概念肯定不会陌生。由于它可以极大地简化处理字符串时的复杂度,因此现在已经在许多Linux实用工具中得到了应用。千万不要以为正则表达式只是Perl、Python、Bash等脚本语言的专利,作为C语言程序员,用户同样可以在自己的程序中运用正则表达式。

标准的C和C++都不支持正则表达式,但有一些函数库可以辅助C/C++程序员完成这一功能,其中最著名的当数Philip Hazel的Perl-Compatible Regular Expression库,许多Linux发行版本都带有这个函数库。

编译正则表达式

为了提高效率,在将一个字符串与正则表达式进行比较之前,首先要用regcomp()函数对它进行编译,将其转化为regex_t结构:

int regcomp(regex_t *preg, const char *regex, int cflags);



参数regex是一个字符串,它代表将要被编译的正则表达式;参数preg指向一个声明为regex_t的数据结构,用来保存编译结果;参数cflags决定了正则表达式该如何被处理的细节。

如果函数regcomp()执行成功,并且编译结果被正确填充到preg中后,函数将返回0,任何其它的返回结果都代表有某种错误产生。

匹配正则表达式

一旦用regcomp()函数成功地编译了正则表达式,接下来就可以调用regexec()函数完成模式匹配:

int regexec(const  regex_t  *preg,  const  char *string, size_t nmatch,regmatch_t pmatch[], int eflags);
typedef struct {
  regoff_t rm_so;
  regoff_t rm_eo;
} regmatch_t;



参数preg指向编译后的正则表达式,参数string是将要进行匹配的字符串,而参数nmatch和pmatch则用于把匹配结果返回给调用程序,最后一个参数eflags决定了匹配的细节。

在调用函数regexec()进行模式匹配的过程中,可能在字符串string中会有多处与给定的正则表达式相匹配,参数pmatch就是用来保存这些匹配位置的,而参数nmatch则告诉函数regexec()最多可以把多少个匹配结果填充到pmatch数组中。当regexec()函数成功返回时,从string+pmatch[0].rm_so到string+pmatch[0].rm_eo是第一个匹配的字符串,而从string+pmatch[1].rm_so到string+pmatch[1].rm_eo,则是第二个匹配的字符串,依此类推。

释放正则表达式

无论什么时候,当不再需要已经编译过的正则表达式时,都应该调用函数regfree()将其释放,以免产生内存泄漏。

void regfree(regex_t *preg);



函数regfree()不会返回任何结果,它仅接收一个指向regex_t数据类型的指针,这是之前调用regcomp()函数所得到的编译结果。

如果在程序中针对同一个regex_t结构调用了多次regcomp()函数,POSIX标准并没有规定是否每次都必须调用regfree()函数进行释放,但建议每次调用regcomp()函数对正则表达式进行编译后都调用一次regfree()函数,以尽早释放占用的存储空间。

报告错误信息

如果调用函数regcomp()或regexec()得到的是一个非0的返回值,则表明在对正则表达式的处理过程中出现了某种错误,此时可以通过调用函数regerror()得到详细的错误信息。

size_t regerror(int errcode, const regex_t *preg, char *errbuf, size_t errbuf_size);



参数errcode是来自函数regcomp()或regexec()的错误代码,而参数preg则是由函数regcomp()得到的编译结果,其目的是把格式化消息所必须的上下文提供给regerror()函数。在执行函数regerror()时,将按照参数errbuf_size指明的最大字节数,在errbuf缓冲区中填入格式化后的错误信息,同时返回错误信息的长度。

应用正则表达式

最后给出一个具体的实例,介绍如何在C语言程序中处理正则表达式。

#include <stdio.h>;
#include <sys/types.h>;
#include <regex.h>;

/* 取子串的函数 */
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;
}
/* 主程序 */
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;
  /* 编译正则表达式*/
  pattern = argv[1];
  z = regcomp(&reg, pattern, cflags);
  if (z != 0){
    regerror(z, &reg, ebuf, sizeof(ebuf));
    fprintf(stderr, "%s: pattern '%s' \n", ebuf, pattern);
    return 1;
  }
  /*  逐行处理输入的数据 */
  while(fgets(lbuf, sizeof(lbuf), stdin)) {
    ++lno;
    if ((z = strlen(lbuf)) >; 0 && lbuf[z-1] == '\n')
      lbuf[z - 1] = 0;
    /* 对每一行应用正则表达式进行匹配 */
    z = regexec(&reg, lbuf, nmatch, pm, 0);
    if (z == REG_NOMATCH) continue;
    else if (z != 0) {
      regerror(z, &reg, ebuf, sizeof(ebuf));
      fprintf(stderr, "%s: regcom('%s')\n", ebuf, lbuf);
      return 2;
    }
    /* 输出处理结果 */
    for (x = 0; x < nmatch && pm[x].rm_so != -1; ++ x) {
      if (!x) printf("%04d: %s\n", lno, lbuf);
      printf("  $%d='%s'\n", x, substr(lbuf, pm[x].rm_so, pm[x].rm_eo));
    }
  }
  /* 释放正则表达式  */
  regfree(&reg);
  return 0;
}



上述程序负责从命令行获取正则表达式,然后将其运用于从标准输入得到的每行数据,并打印出匹配结果。执行下面的命令可以编译并执行该程序:

#  gcc regexp.c -o regexp
#  ./regexp  'regex[a-z]*' < regexp.c
0003: #include <regex.h>;
  $0='regex'
0027:   regex_t reg;
  $0='regex'
0054:     z = regexec(&reg, lbuf, nmatch, pm, 0);
  $0='regexec'



小结

对那些需要进行复杂数据处理的程序来说,正则表达式无疑是一个非常有用的工具。本文重点在于阐述如何在C语言中利用正则表达式来简化字符串处理,以便在数据处理方面能够获得与Perl语言类似的灵活性。
作者: linuxmj    时间: 2004-04-13 23:55
标题: 如何在C语言中巧用正则表达式
sed、awk、grep或vi
我只知道vi是编辑器!其他几个劳烦楼主接着介绍一下
作者: bobbycalf    时间: 2004-04-14 12:12
标题: 如何在C语言中巧用正则表达式
谢谢高手,这篇文章似乎可以加为
呵呵
作者: lcd    时间: 2004-04-14 13:12
标题: 如何在C语言中巧用正则表达式
不错,不是楼主的介绍还不知道linux的C中还可以用正则表达式
thanks
作者: xhl    时间: 2004-04-14 16:07
标题: 如何在C语言中巧用正则表达式
不错,收藏!谢谢楼主了
作者: yyii    时间: 2004-04-17 18:47
提示: 作者被禁止或删除 内容自动屏蔽
作者: hoxide    时间: 2004-04-17 18:54
标题: 如何在C语言中巧用正则表达式
我最近看SCO OpenServer程序员参考才知道有c中的正则表达式处理库的,没想到这里楼主也介绍了.

好,支持加精
作者: chfchf    时间: 2004-04-26 12:28
标题: 如何在C语言中巧用正则表达式
好文,支持!
作者: zhangwei_jef    时间: 2004-04-26 12:56
标题: 如何在C语言中巧用正则表达式
支持
作者: freecoder    时间: 2004-04-26 19:10
标题: 如何在C语言中巧用正则表达式
hoxide :    SCO OpenServer程序员参考 能发一份给我吗?
luckyredfox@163.com
作者: li2002    时间: 2004-04-27 08:48
标题: 如何在C语言中巧用正则表达式
以前看过regcomp的介绍,但想起用的时候少~~
作者: 飞灰橙    时间: 2004-04-27 09:01
标题: 如何在C语言中巧用正则表达式
新知识 收藏
作者: liaonianbo    时间: 2006-12-01 14:11
标题: 不知道如何实现反向引用呢
如果需要做类似vi中如下替换  s/\([a-z]\+\)\([0-9]\+\)/\1,\1,\2/g
作者: bzhzhang    时间: 2007-05-09 10:49
http://www.devfront.com:8080/?q=node/140

更为详细
作者: 清汤挂面    时间: 2007-05-09 11:10
这个对汉字的支持很不好,差点被其给害了
作者: goldensunflower    时间: 2007-05-11 12:00
学习
作者: zhoujianxin    时间: 2007-05-11 13:04
posix有正则把。http://www.devfront.com:8080/?q=node/140
如果使用正则反而把简单的事情复杂化了,还不如不用,^_^。个人意见
作者: llslls_007    时间: 2007-05-12 11:49
原帖由 hoxide 于 2004-4-17 18:54 发表
我最近看SCO OpenServer程序员参考才知道有c中的正则表达式处理库的,没想到这里楼主也介绍了.

好,支持加精


有电子版的<SCO OpenServer程序员参考>吗?  也发我一份  不胜感激!!  不知道晚不晚 呵呵!!
llslls_007@hotmail.com

[ 本帖最后由 llslls_007 于 2007-5-12 11:51 编辑 ]
作者: yecheng_110    时间: 2008-01-01 00:20
在调用函数regexec()进行模式匹配的过程中,可能在字符串string中会有多处与给定的正则表达式相匹配,参数pmatch就是用来保存这些匹配位置的,而参数nmatch则告诉函数regexec()最多可以把多少个匹配结果填充到pmatch数组中。当regexec()函数成功返回时,从 string+pmatch[0].rm_so到string+pmatch[0].rm_eo是第一个匹配的字符串,而从string+pmatch [1].rm_so到string+pmatch[1].rm_eo,则是第二个匹配的字符串,依此类推。

似乎这里有误
应该是以下的解释才对
字符串string中会有多处与给定的正则表达式相匹配,应该是匹配第一个就结束了,pmatch保存的应该是用‘()’括起来的Subexpression的位置
10.3.4 Match Results with Subexpressions

When regexec matches parenthetical subexpressions of pattern, it records which parts of string they match. It returns that information by storing the offsets into an array whose elements are structures of type regmatch_t. The first element of the array (index 0) records the part of the string that matched the entire regular expression. Each other element of the array records the beginning and end of the part that matched a single parenthetical subexpression.
— Data Type: regmatch_t

    This is the data type of the matcharray array that you pass to regexec. It contains two structure fields, as follows:

    rm_so
        The offset in string of the beginning of a substring. Add this value to string to get the address of that part.
    rm_eo
        The offset in string of the end of the substring.

— Data Type: regoff_t

    regoff_t is an alias for another signed integer type. The fields of regmatch_t have type regoff_t.

The regmatch_t elements correspond to subexpressions positionally; the first element (index 1) records where the first subexpression matched, the second element records the second subexpression, and so on. The order of the subexpressions is the order in which they begin.

When you call regexec, you specify how long the matchptr array is, with the nmatch argument. This tells regexec how many elements to store. If the actual regular expression has more than nmatch subexpressions, then you won't get offset information about the rest of them. But this doesn't alter whether the pattern matches a particular string or not.

If you don't want regexec to return any information about where the subexpressions matched, you can either supply 0 for nmatch, or use the flag REG_NOSUB when you compile the pattern with regcomp.

[ 本帖最后由 yecheng_110 于 2008-1-1 00:25 编辑 ]
作者: anthony1983    时间: 2008-01-01 13:57
一直知道C语言里有处理正则表达式的库,但是从来没用过,而是在C中调用其他脚本语言来处理正则。
作者: flw    时间: 2008-01-01 14:02
pcre 很强大,很邪恶。
作者: songpure520    时间: 2008-01-01 16:26
我也顶一下!!!一向以为C没有正则,看到楼主的文章,才知道有!
作者: zhhui2000    时间: 2008-01-02 08:48
感谢分享,哪儿有开源的库就好了,什么环境下都可用。
作者: yjm0573    时间: 2008-01-02 09:51
pcre_compile
pcre_exec

这两个也能实现
作者: lysde    时间: 2008-01-02 10:59
谢楼主,这个牛啊!
作者: 南无小和尚    时间: 2009-06-26 14:10
运行了下楼主的程序,怎么是:Segmentation fault
#include <stdio.h>
#include <sys/types.h>
#include <stdlib.h>
#include <string.h>
#include <regex.h>
/* 取子串的函数 */
static char* substr(const char*str, unsigned start, unsigned end)
{
&nbsp;&nbsp;&nbsp;&nbsp;unsigned n = end - start;
&nbsp;&nbsp;&nbsp;&nbsp;static char stbuf[256];
&nbsp;&nbsp;&nbsp;&nbsp;strncpy(stbuf, str + start, n);
&nbsp;&nbsp;&nbsp;&nbsp;stbuf[n] = 0;
&nbsp;&nbsp;&nbsp;&nbsp;return stbuf;
}
/* 主程序 */
int main(int argc, char** argv)
{
&nbsp;&nbsp;&nbsp;&nbsp;char * pattern;
&nbsp;&nbsp;&nbsp;&nbsp;int x, z, lno = 0, cflags = 0;
&nbsp;&nbsp;&nbsp;&nbsp;char ebuf[128], lbuf[256];
&nbsp;&nbsp;&nbsp;&nbsp;regex_t reg;
&nbsp;&nbsp;&nbsp;&nbsp;regmatch_t pm[10];
&nbsp;&nbsp;&nbsp;&nbsp;const size_t nmatch = 10;
&nbsp;&nbsp;&nbsp;&nbsp;/* 编译正则表达式*/
&nbsp;&nbsp;&nbsp;&nbsp;pattern = argv[1];
&nbsp;&nbsp;&nbsp;&nbsp;z = regcomp(&reg, pattern, cflags);
&nbsp;&nbsp;&nbsp;&nbsp;if (z != 0){
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;regerror(z, &reg, ebuf, sizeof(ebuf));
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;fprintf(stderr, "%s: pattern '%s' \n", ebuf, pattern);
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return 1;
&nbsp;&nbsp;&nbsp;&nbsp;}
&nbsp;&nbsp;&nbsp;&nbsp;/*  逐行处理输入的数据 */
&nbsp;&nbsp;&nbsp;&nbsp;while(fgets(lbuf, sizeof(lbuf), stdin)) {
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;++lno;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if ((z = strlen(lbuf)) >0 && lbuf[z-1] == '\n')
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;lbuf[z - 1] = 0;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;/* 对每一行应用正则表达式进行匹配 */
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;z = regexec(&reg, lbuf, nmatch, pm, 0);
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if (z == REG_NOMATCH) continue;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;else if (z != 0) {
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;regerror(z, &reg, ebuf, sizeof(ebuf));
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;fprintf(stderr, "%s: regcom('%s')\n", ebuf, lbuf);
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return 2;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;/* 输出处理结果 */
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;for (x = 0; x < nmatch && pm[x].rm_so != -1; ++ x) {
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if (!x) printf("%04d: %s\n", lno, lbuf);
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;printf("  $%d='%s'\n", x, substr(lbuf, pm[x].rm_so, pm[x].rm_eo));
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}
&nbsp;&nbsp;&nbsp;&nbsp;}
&nbsp;&nbsp;&nbsp;&nbsp;/* 释放正则表达式  */
&nbsp;&nbsp;&nbsp;&nbsp;regfree(&reg);
&nbsp;&nbsp;&nbsp;&nbsp;return 0;
}


作者: wrongch    时间: 2009-06-26 14:14
真的很不错。
作者: 南无小和尚    时间: 2009-06-26 14:15
标题: 回复 #27 wrongch 的帖子
啥很不错啊??
作者: shihyu    时间: 2009-06-27 07:15
我运行也 Segmentation fault
作者: baopbird2005    时间: 2009-07-03 08:49
牛人。
作者: yulihua49    时间: 2009-07-04 22:02
原帖由 fwizard 于 2004-4-13 22:22 发表
看到大家讨论这方面的东西,作点贡献聊表各位高手对这个版快的无私奉献

如果用户熟悉Linux下的sed、awk、grep或vi,那么对正则表达式这一概念肯定不会陌生。由于它可以极大地简化处理字符串时的复杂 ...

普及这个知识很必要。不会正则表达式,就不能算懂UNIX,懂C。
作者: houtinghua    时间: 2009-07-04 22:46
posix的正泽库好像不支持非贪婪算法  很不爽
作者: yulihua49    时间: 2009-07-06 14:27
原帖由 houtinghua 于 2009-7-4 22:46 发表
posix的正泽库好像不支持非贪婪算法  很不爽

  什么叫 非贪婪算法?请点拨一下。
作者: 南无小和尚    时间: 2009-07-07 00:22
标题: 回复 #33 yulihua49 的帖子
google点拨下:
http://www.smashingmagazine.com/ ... egular-expressions/
这篇写的很经典
作者: houtinghua    时间: 2009-07-07 10:42
原帖由 yulihua49 于 2009-7-6 14:27 发表

  什么叫 非贪婪算法?请点拨一下。


目标文本为 <tr><td>asdf</td></tr><tr><td>abc</td></tr><tr><td>def</td></tr>
我要取第一行
.net下的表达式为<tr>.*?</tr>    ?是限定符   如果没有  就会把这3行都取出来
linux下的grep 命令可以加  -o 来启动非贪婪模式

posix下的自带的不支持非贪婪模式     要不就是有而我不知道罢了   欢迎指正
作者: iLRainyday    时间: 2009-07-07 21:01
在<linux programming by examples>一书中专门介绍了regex在C中的使用
作者: ExclusivePig    时间: 2009-09-15 14:44
原帖由 yecheng_110 于 2008-1-1 00:20 发表

似乎这里有误
应该是以下的解释才对
字符串string中会有多处与给定的正则表达式相匹配,应该是匹配第一个就结束了,pmatch保存的应该是用‘()’括起来的Subexpression的位置



跪求高手继续解释。。。我目前在用prce库,但总是只能匹配一个结果,对于多个匹配无法得到,我用的是pcre_compile,和prce_exec
作者: supercyper    时间: 2009-09-15 15:33

作者: wesleyluo    时间: 2009-10-30 14:06
可以发贴了?
作者: tulip0425    时间: 2009-10-30 15:05
标题: 回复 #1 fwizard 的帖子
支持,好文章,又长见识了
作者: yulihua49    时间: 2009-11-02 14:56
原帖由 清汤挂面 于 2007-5-9 11:10 发表
这个对汉字的支持很不好,差点被其给害了

不能滥用正则表达式,各种字符集下很可能不能处理多国文字。

我们一般只用于词法分析。
作者: yulihua49    时间: 2009-11-02 14:59
原帖由 liaonianbo 于 2006-12-1 14:11 发表
如果需要做类似vi中如下替换  s/\([a-z]\+\)\([0-9]\+\)/\1,\1,\2/g

分两步做。
1:使用正则表达式检索目标。
2:使用替换函数将目标替换成结果。
作者: yulihua49    时间: 2009-11-02 15:01
原帖由 zhhui2000 于 2008-1-2 08:48 发表
感谢分享,哪儿有开源的库就好了,什么环境下都可用。

LINUX,UNIX自带,无需另外的库。
作者: yulihua49    时间: 2009-11-02 15:10
原帖由 ExclusivePig 于 2009-9-15 14:44 发表



跪求高手继续解释。。。我目前在用prce库,但总是只能匹配一个结果,对于多个匹配无法得到,我用的是pcre_compile,和prce_exec

给你一个程序吧,把环境变量里的$展开:


  1. static char env_src[]="\\$[{(]{0,1}([A-Za-z_][0-9A-Za-z_]*)[})]{0,1}";
  2. int substitute_env(char *line)
  3. {
  4. char env[256];
  5. char *p=line,*envp,*getenv();
  6. regmatch_t pmatch[REGNUM];
  7. int i;
  8.         if(!line) return 0;
  9.         while(!(i=regexec(&env_rp,p,REGNUM,pmatch,0))) {  //匹配多个
  10.                for(envp=p+pmatch[1].rm_so;envp<p+pmatch[1].rm_eo;envp++) {
  11.                                 env[i++]=*envp;
  12.                       }
  13.                  env[i]=0;
  14.                  envp=getenv(env);
  15.                 if(!envp) envp=".";
  16.                 p=strsubst(p+pmatch[0].rm_so, pmatch[0].rm_eo - pmatch[0].rm_so,envp);//p指向替换后的地址,下一轮从此开始继续匹配
  17.            }
  18.             return 0;
  19. }
复制代码


唉,这问题也问?能匹配1个就能匹配多个,程序处理呗。

[ 本帖最后由 yulihua49 于 2009-11-2 15:21 编辑 ]




欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2