加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

正则库pcre使用例程

发布时间:2020-12-14 02:06:06 所属栏目:百科 来源:网络整理
导读:分类: LINUX 例子1: # include stdio . h # include string . h # include pcre . h /********************************************************************** *#include pcre.h * *parameters: src: string * * pattern: regular expression * *return:

分类: LINUX

例子1:

#include <stdio.h>
#include <string.h>
#include <pcre.h>

/**********************************************************************
*#include <pcre.h> *
*parameters: src: string *
* pattern: regular expression *
*return: match >= 0 and nomatch < 0 *
*date: 2008-03-12 *
*developer: Leon *
**********************************************************************/

int fun_ismatch( char* src, char* pattern)
{
pcre *re;
const char *error;
int erroffset;
int rc;

if( (re = pcre_compile( pattern, 0, &error, &erroffset, NULL)) == NULL) goto bad;
if( (rc = pcre_exec( re, NULL, src, strlen(src), 0)) < 0) goto bad;

free(re);
return rc;
bad:
free(re);
return -1;
}

int main (int argc, char **argv)
{
struct timeval tpstart,tpend;

const char *pattern = "^http://.+?btchina.net/download.php*";
argv[1] = "http://dl1.www2.btchina.net/download.php?s=1125f72b0f6f6887&attachmentid=1064643@http://bt3.btchina.net/";

gettimeofday( &tpstart, NULL);
int result = fun_ismatch( argv[1], (char*)pattern);
gettimeofday( &tpend, NULL);

printf ("result: %dnuse time: %un", result, tpend.tv_usec - tpstart.tv_usec);

return;
}

例子2:

#include <stdio.h>
#include <string.h>
#include <pcre.h>

#define OVECCOUNT 30 /* should be a multiple of 3 */
#define EBUFLEN 128
#define BUFLEN 1024

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>(.*)</title>";

printf("String : %sn", src);
printf("Pattern: "%s"n", pattern);


re = pcre_compile(pattern, NULL);
if (re == NULL) {
printf("PCRE compilation failed at offset %d: %sn", erroffset, error);
return 1;
}

rc = pcre_exec(re, ovector, OVECCOUNT);
if (rc < 0) {
if (rc == PCRE_ERROR_NOMATCH) printf("Sorry,no match ...n");
else printf("Matching error %dn", rc);
free(re);
return 1;
}

printf("nOK,has matched ...nn");

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: %.*sn", i, substring_length, substring_start);
}

free(re);
return 0;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读