正则库pcre使用例程

前端之家收集整理的这篇文章主要介绍了正则库pcre使用例程前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

分类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: %d\nuse time: %u\n", 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 : %s\n", src);
printf("Pattern: \"%s\"\n", pattern);


re = pcre_compile(pattern, NULL);
if (re == NULL) {
printf("PCRE compilation Failed at offset %d: %s\n", 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 %d\n", rc);
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);
}

free(re);
return 0;
}

原文链接:https://www.f2er.com/regex/362450.html

猜你在找的正则表达式相关文章