POSIX C正则库

POSIX C正则库
****2011年 02月 08日 星期二 00:35:38 CST

  标准C库中没有正则表达式相关的函数,一般来说C中使用两种正则表达式库,一为POSIX C正则库,二为perl正则库PCRE。相比较而言PCRE要强大些,POSIX C正则库就足够使用。
  POSIX C正则库很好使用,一共只需掌握4个函数(regcomp, regexec, regerror, regfree)的使用即可,在 UNIX/Linux下最好的材料当然是man page,可以使用命令man regex查看POSIX regex functions,本文的最后附一份此man page。或者是在Linux下使用更详细的info page,C-s regex查找到* regcomp: (libc)POSIX Regexp Compilation.节,info page更详细些,在讲regerror节甚至给出了一个一般情况下使用的函数char *get_regerror (int errcode, regex_t *compiled);
    1. regcomp
  该函数的原型如下:
int regcomp(regex_t *preg, const char *regex,int cflags); 
  POSIX C正则库为了提高效率,在将一个字符串与正则表达式进行比较之前,首先要用regcomp()函数对它进行编译,将其转化为regex_t类型,可以在/usr/include/regex.h中看到该类型是结构struct re_pattern_buffer的typedef。regex字符形式的正则表达式串。
  cflags有以下几种:
  • REG_EXTENDED
  • 启用POSIX正则库扩展,关于该扩展的详细信息可参考POSIX规范。
  • REG_ICASE
  • 忽略大小写,相当于grep的-i参数。
  • REG_NOSUB
  • 不要存储子表达式
  • REG_NEWLINE
  • 把换行符作为多行的分隔符,这样'$'可匹配每一行的行尾,'^'匹配每一行的行首,'.'不匹配换行符,[^...]不匹配新行
    1. regexec
  该函数的原型如下:
int regexec (regex_t *compiled, char *string, size_t nmatch, regmatch_t matchptr [], int eflags);
  nmatch指明matchptr数组的数目,该数目是compiled->re_nsub+1,也可以让nmatch为0,matchptr为NULL,表示不要保存子表达式。eflags通常为0。
  匹配结束后,匹配到的子表达式在串中的偏移保存在regmatch_t结构中,该结构有两个成员:
  • rm_so
  • 子表达式的起始偏移
  • rm_eo
  • 子表达式的结束偏移
    1. regfree
  该函数的原型如下:
void regfree(regex_t *preg);
  函数regfree()不会返回任何结果,它仅接收一个指向regex_t数据类型的指针,这是之前调用regcomp()函数所得到的编译结果。 如果在程序中针对同一个regex_t结构调用了多次regcomp()函数,POSIX标准并没有规定是否每次都必须调用regfree()函数进行释放,但建议每次调用regcomp()函数对正则表达式进行编译后都调用一次regfree()函数,以尽早释放占用的存储空间。
    1. 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缓冲区中填入格式化后的错误信息,同时返回错误信息的长度。

 

  POSIX C正则表达式实例:(该代码来自于互联网,很好的示例了POSIX C正则库的几个函数)
/* regexamp_1.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 regex; 
	regmatch_t pm[10]; 
	const size_t nmatch = 10; 
	/* 编译正则表达式*/ 
	pattern = argv[1]; 
	z = regcomp(®ex, pattern, cflags); 
	if (z != 0){ 
		regerror(z, ®ex, 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(®ex, lbuf, nmatch, pm, 0);  
		if (z == REG_NOMATCH)
			continue; 
		else if (z != 0) { 
			regerror(z, ®ex, 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(®ex); 
	return 0; 
}
  编译并运行该代码如下:
$ cc -o regexamp_1 regexamp_1.c            
$ ./regexamp_1 'regex[a-z]*' < regexamp_1.c
0003: #include  
 $0='regex'
0020:   regex_t regex; 
 $0='regex'
0025:   z = regcomp(®ex, pattern, cflags); 
 $0='regex'
0027:           regerror(z, ®ex, ebuf, sizeof(ebuf)); 
 $0='regex'
0038:           z = regexec(®ex, lbuf, nmatch, pm, 0);  
 $0='regexec'
0042:                   regerror(z, ®ex, ebuf, sizeof(ebuf)); 
 $0='regex'
0055:   regfree(®ex); 
 $0='regex'

 

  附regex的man page如下:
REGCOMP(3)		   Linux Programmer's Manual		    REGCOMP(3)



NAME
       regcomp, regexec, regerror, regfree - POSIX regex functions

SYNOPSIS
       #include 
       #include 

       int regcomp(regex_t *preg, const char *regex, int cflags);
       int regexec(const  regex_t  *preg,  const  char *string, size_t nmatch,
		   regmatch_t pmatch[], int eflags);
       size_t regerror(int errcode, const regex_t *preg, char *errbuf,	size_t
		       errbuf_size);
       void regfree(regex_t *preg);

POSIX REGEX COMPILING
       regcomp()  is  used to compile a regular expression into a form that is
       suitable for subsequent regexec() searches.

       regcomp() is supplied with preg, a pointer to a pattern buffer  storage
       area;  regex, a pointer to the null-terminated string and cflags, flags
       used to determine the type of compilation.

       All regular expression searching must be done via  a  compiled  pattern
       buffer,	thus  regexec()	 must always be supplied with the address of a
       regcomp() initialized pattern buffer.

       cflags may be the bitwise-or of one or more of the following:

       REG_EXTENDED
	      Use POSIX Extended Regular Expression syntax  when  interpreting
	      regex.   If  not	set,  POSIX Basic Regular Expression syntax is
	      used.

       REG_ICASE
	      Do not differentiate case.  Subsequent regexec() searches	 using
	      this pattern buffer will be case insensitive.

       REG_NOSUB
	      Support  for  substring  addressing  of matches is not required.
	      The nmatch and pmatch parameters to regexec() are ignored if the
	      pattern buffer supplied was compiled with this flag set.

       REG_NEWLINE
	      Match-any-character operators don't match a newline.

	      A	 non-matching list ([^...])  not containing a newline does not
	      match a newline.

	      Match-beginning-of-line operator (^) matches  the	 empty	string
	      immediately  after  a newline, regardless of whether eflags, the
	      execution flags of regexec(), contains REG_NOTBOL.

	      Match-end-of-line operator ($) matches the empty string  immedi-
	      ately  before  a	newline, regardless of whether eflags contains
	      REG_NOTEOL.

POSIX REGEX MATCHING
       regexec() is used to match a null-terminated string against the precom-
       piled  pattern  buffer,	preg.	nmatch	and pmatch are used to provide
       information regarding the location of any matches.  eflags may  be  the
       bitwise-or  of  one  or	both  of REG_NOTBOL and REG_NOTEOL which cause
       changes in matching behaviour described below.

       REG_NOTBOL
	      The match-beginning-of-line operator always fails to match  (but
	      see  the	compilation  flag  REG_NEWLINE above) This flag may be
	      used when different portions of a string are passed to regexec()
	      and the beginning of the string should not be interpreted as the
	      beginning of the line.

       REG_NOTEOL
	      The match-end-of-line operator always fails to  match  (but  see
	      the compilation flag REG_NEWLINE above)

   BYTE OFFSETS
       Unless  REG_NOSUB was set for the compilation of the pattern buffer, it
       is possible to obtain substring match addressing	 information.	pmatch
       must be dimensioned to have at least nmatch elements.  These are filled
       in by regexec() with substring match addresses.	Any  unused  structure
       elements will contain the value -1.

       The  regmatch_t	structure  which  is  the type of pmatch is defined in
       regex.h.

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

       Each rm_so element that is not -1 indicates the	start  offset  of  the
       next  largest  substring	 match	within the string.  The relative rm_eo
       element indicates the end offset of the match.

POSIX ERROR REPORTING
       regerror() is used to turn the error codes that can be returned by both
       regcomp() and regexec() into error message strings.

       regerror() is passed the error code, errcode, the pattern buffer, preg,
       a pointer to a character string buffer, errbuf, and  the	 size  of  the
       string buffer, errbuf_size.  It returns the size of the errbuf required
       to contain the null-terminated error message string.   If  both	errbuf
       and  errbuf_size	 are  non-zero,	 errbuf	 is  filled  in with the first
       errbuf_size - 1 characters of the error message and a terminating null.

POSIX PATTERN BUFFER FREEING
       Supplying  regfree()  with a precompiled pattern buffer, preg will free
       the memory allocated to the pattern buffer by  the  compiling  process,
       regcomp().

RETURN VALUE
       regcomp()  returns  zero	 for a successful compilation or an error code
       for failure.

       regexec() returns zero for a successful match or REG_NOMATCH for	 fail-
       ure.

ERRORS
       The following errors can be returned by regcomp():

       REG_BADBR
	      Invalid use of back reference operator.

       REG_BADPAT
	      Invalid use of pattern operators such as group or list.

       REG_BADRPT
	      Invalid  use  of	repetition  operators such as using `*' as the
	      first character.

       REG_EBRACE
	      Un-matched brace interval operators.

       REG_EBRACK
	      Un-matched bracket list operators.

       REG_ECOLLATE
	      Invalid collating element.

       REG_ECTYPE
	      Unknown character class name.

       REG_EEND
	      Non specific error.  This is not defined by POSIX.2.

       REG_EESCAPE
	      Trailing backslash.

       REG_EPAREN
	      Un-matched parenthesis group operators.

       REG_ERANGE
	      Invalid use of the range operator, eg. the ending point  of  the
	      range occurs prior to the starting point.

       REG_ESIZE
	      Compiled	regular	 expression  requires  a pattern buffer larger
	      than 64Kb.  This is not defined by POSIX.2.

       REG_ESPACE
	      The regex routines ran out of memory.

       REG_ESUBREG
	      Invalid back reference to a subexpression.

CONFORMING TO
       POSIX.1-2001.

SEE ALSO
       regex(7), GNU regex manual




GNU				  1998-05-08			    REGCOMP(3)

posted @ 2010-10-15 13:34  陈龙的blog  阅读(4431)  评论(0编辑  收藏  举报