文章来自http://hi.baidu.com/intsign/blog/item/dc88f313198da5d2a6866951.html
最段时间可能会用到C语言进行字符串处理,PCRE正则表达式是很重要的一个工具,关于C语言的接口的例子在网上不是很多,在此收录一下。
#include <stdio.h>
#include <pcre.h>
#include <string.h>
#define OVECCOUNT 30 /*should be a multiple of 3*/
#define PCRE_STATIC /*static compile option */
#define EBUFLEN 128
#define BUFLEN 65536
int main(){
pcre *re;
const char *error;
int erroffset;
int ovector[OVECCOUNT];
int rc,i;
char src[]="111<title>Hello World</title>222";
char pattern[]="<title>(.*)</(tit)le>";
printf("string:%s\n",src);
printf("pattern:%s\n",pattern);
re=pcre_compile(pattern,0,&error,&erroffset,NULL);
if(re==NULL){
printf("pcre compilation failed at offset %d:%s\n",erroffset,error);
return 1;
}
rc=pcre_exec(re,NULL,src,strlen(src),0,0,ovector,OVECCOUNT);
if(rc<0){
if(rc==PCRE_ERROR_NOMATCH){
printf("sorry ,no match ...\n");
}
else{
printf("matching error %d\n",rc);
pcre_free(re);
return 1;
}
}
printf("\nok ,has matched ...\n\n");
for(i=0;i<rc;i++){
char *substring_start=src+ovector[2*i];
int substring_length=ovector[2*i+1]-ovector[2*i];
printf("$%2d :%.*s\n",i,substring_length,substring_start); /* 注意这里 %.*的用法 */
}
pcre_free(re);
return 0;
}