正则表达式被称为字符串处理的魔术师,对于复杂的字符串操作非常有用。由于标准c没有自带的正则库,因此在c平台下一般采用pcre库
以Imagemagick中提取Crop区域为例:
#include "pcre.h"
using namespace std;
#pragma comment(lib,"pcre.lib")
int main()
{
pcre* re;
cout<<"hello"<<endl;
const char *error;
int erroffset;
int ovector[100];
int rc, i;
char src [] ="{/"v/":/"-1,2,0,0,0,0/",/"re/":[/"283,100,8,8/",/"351,106,7,7/"],/"s/":/"640/",/"cr/":[/"3:/":/"0,1,640,425/"]}";
char cr_pattern[]= "/"cr/"://[/"//d+://d+/":/"(//d+,){3}(//d+)/"//]";
printf("String : %s/n", src);
printf("Pattern: %s/n", v_pattern);
re = pcre_compile(cr_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, 100); //ovecter中存储的是匹配的起始和结束的位置
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");
printf("%d/n",rc);
for (i = 0; i < rc; i++)
{
char *substring_start = src + ovector[2*i];
int substring_length = ovector[2*i+1] - ovector[2*i];
printf("%d,%d;%d,%d/n",ovector[0],ovector[1],ovector[2],ovector[3]);
printf("%2d: %.*s/n", i, substring_length, substring_start);
}
free(re);
return 0;
}