Linux下POSIX正则表达式API使用

来源:互联网 发布:手机mac怎么改 编辑:程序博客网 时间:2024/06/05 05:00


一、概述

在Linux环境中,经常使用正则表达式,如grep、sed、find等等,目前正则表达式有2中不同的标准,分别是Perl标准和POSIX标准,这2种风格,大体相同,稍有差别。在 C/C++的标准库均不支持表达式,不过在C++11标准中,貌似引入了boost的正则库,在Linux环境中也自带了一组API支持正则,即POSIX标准的C接口。
常用的一组API如下:
int regcomp (regex_t *compiled, const char *pattern, int cflags);
int regexec (regex_t *compiled, char *string, size_t nmatch, 
                   regmatch_t matchptr [], int eflags);
void regfree (regex_t *compiled);
size_t regerror (int errcode, regex_t *compiled, char *buffer, size_t length);


二、实例解析

代码RegexDemo.c

代码的注释,已经很清楚,无需多言,如有错误,欢迎指正。

/*************************************************************************> File Name: RegexDemo.c> Author: KentZhang> Mail: zhchk2010@qq.com > Created Time: 2015年12月12日 星期六 09时22分26秒 ************************************************************************/#include<stdio.h>#include<sys/types.h>#include<regex.h>#include<string.h>#include<stdlib.h>#define BUFSIZE 256int main(){/************************************************************************************************ 1、编译正则表达式regcomp 2、匹配正则表达式regexec 3、释放正则表达式regfree************************************************************************************************/char bufError[BUFSIZE] = {0};const char* strRule = "c[a-z]t";         //正则表达式const char* strSrc = "123citabcat+-cot"; //源字符串regex_t reg;                         //用来存放编译后的正则表达式int nResult = regcomp(&reg, strRule, 0); //编译正则表达式if (0 != nResult){                       //如果出错,获取出错信息regerror(nResult, &reg, bufError, sizeof(bufError));printf("regcomp() failed:%s\n", bufError);}regmatch_t pm[1];                       //这个结构体数组用来存放匹配的结果信息,本例是循环获取所有字串,数组长度为1即可const size_t nMatch = 1;                //表示上面数组的长度char bufMatch[BUFSIZE];      /**************************************************************************************************    1、regmatch_t 这个结构体非常重要,包含2个成员rm_so,rm_eo,即匹配到的子串的首,尾在源字符串的偏移位置   显然根据源字符串首指针和这2个成员,可以获取字串的内容        2、下面的regexec函数的第二个参数即源字符串的首指针,当然必须是UTF-8字符串,若要循环匹配,源字符串的指针   必须不断后移,因为前面的已经匹配过      **************************************************************************************************/while(!regexec(&reg, strSrc, nMatch, pm, 0)){ //循环匹配出所有子串bzero(bufMatch,sizeof(bufMatch));strncpy(bufMatch, strSrc+pm[0].rm_so, pm[0].rm_eo-pm[0].rm_so); //取出匹配的结果,并打印printf("Match result is:%s, rm_so=%d, rm_eo=%d\n", bufMatch, pm[0].rm_so, pm[0].rm_eo);strSrc += pm[0].rm_eo;             //将指针后移,接着匹配if ('\0' == *strSrc)break;}regfree(&reg);return 0;}

编译执行后的结果:

kent@ubuntu:~/workspace$ ./a.out
Match result is:cit, rm_so=3, rm_eo=6
Match result is:cat, rm_so=2, rm_eo=5
Match result is:cot, rm_so=2, rm_eo=5




0 0
原创粉丝点击