[精彩] 如何在C语言中巧用正则表达式

来源:百度文库 编辑:神马文学网 时间:2024/04/28 19:28:42
看到大家讨论这方面的东西,作点贡献聊表各位高手对这个版快的无私奉献 :oops:
如果用户熟悉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 ;
#include ;
#include ;
/* 取子串的函数 */
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(®, pattern, cflags);
if (z != 0){
regerror(z, ®, 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(®, lbuf, nmatch, pm, 0);
if (z == REG_NOMATCH) continue;
else if (z != 0) {
regerror(z, ®, 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(®);
return 0;
}
上述程序负责从命令行获取正则表达式,然后将其运用于从标准输入得到的每行数据,并打印出匹配结果。执行下面的命令可以编译并执行该程序:
#  gcc regexp.c -o regexp
#  ./regexp  'regex[a-z]*' < regexp.c
0003: #include ;
$0='regex'
0027:   regex_t reg;
$0='regex'
0054:     z = regexec(®, lbuf, nmatch, pm, 0);
$0='regexec'
小结
对那些需要进行复杂数据处理的程序来说,正则表达式无疑是一个非常有用的工具。本文重点在于阐述如何在C语言中利用正则表达式来简化字符串处理,以便在数据处理方面能够获得与Perl语言类似的灵活性。
linuxmj 回复于:2004-04-13 23:55:58
sed、awk、grep或vi
我只知道vi是编辑器!其他几个劳烦楼主接着介绍一下
bobbycalf 回复于:2004-04-14 12:12:37
谢谢高手,这篇文章似乎可以加为精
呵呵
lcd 回复于:2004-04-14 13:12:14
不错,不是楼主的介绍还不知道linux的C中还可以用正则表达式
thanks
xhl 回复于:2004-04-14 16:07:16
不错,收藏!谢谢楼主了
yyii 回复于:2004-04-17 18:47:02
妙文也,谢谢楼主了
hoxide 回复于:2004-04-17 18:54:50
我最近看SCO OpenServer程序员参考才知道有c中的正则表达式处理库的,没想到这里楼主也介绍了.
好,支持加精
chfchf 回复于:2004-04-26 12:28:22
好文,支持!
zhangwei_jef 回复于:2004-04-26 12:56:22
支持
freecoder 回复于:2004-04-26 19:10:03
hoxide :    SCO OpenServer程序员参考 能发一份给我吗?
luckyredfox@163.com
li2002 回复于:2004-04-27 08:48:11
以前看过regcomp的介绍,但想起用的时候少~~
飞灰橙 回复于:2004-04-27 09:01:24
新知识 收藏
liaonianbo 回复于:2006-12-01 14:11:43
如果需要做类似vi中如下替换  s/\([a-z]\+\)\([0-9]\+\)/\1,\1,\2/g
bzhzhang 回复于:2007-05-09 10:49:24
http://www.devfront.com:8080/?q=node/140
更为详细
清汤挂面 回复于:2007-05-09 11:10:58
这个对汉字的支持很不好,差点被其给害了
goldensunflower 回复于:2007-05-11 12:00:20
学习
zhoujianxin 回复于:2007-05-11 13:04:01
posix有正则把。http://www.devfront.com:8080/?q=node/140
如果使用正则反而把简单的事情复杂化了,还不如不用,^_^。个人意见
llslls_007 回复于:2007-05-12 11:49:51
引用:原帖由 hoxide 于 2004-4-17 18:54 发表
我最近看SCO OpenServer程序员参考才知道有c中的正则表达式处理库的,没想到这里楼主也介绍了.
好,支持加精
有电子版的吗?  也发我一份  不胜感激!!  不知道晚不晚 呵呵!!
[email]llslls_007@hotmail.com[/email]
[ 本帖最后由 llslls_007 于 2007-5-12 11:51 编辑 ]
yecheng_110 回复于:2008-01-01 00:20:55
引用:
在调用函数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.