Tuesday, August 21, 2007

Pattern Matching with PCRE Library

Pattern matching is wonderful with Perl and when it is comes to C it is nice to build wonderful applications.

#include <ctype.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#include <locale.h>
#include <errno.h>
#include <pcre.h>

int main(int argc,char *argv[])
{
pcre *re;
char cgets[250];
const char *error;
int erroffset;
int retexec;
re = pcre_compile("^(gnayiru|thingal|chevvai|budhan|viyazhan|velli|sani)$",0,&error,&erroffset,NULL);
if( re )
{
while(1){
printf("Enter the details you wish to match:");
fgets(cgets,250,stdin);
cgets[strlen(cgets)-1] = '\0';
retexec = pcre_exec(re,NULL,cgets,strlen(cgets),0,PCRE_PARTIAL,NULL,0);
switch( retexec)
{
case PCRE_ERROR_NOMATCH:
printf("No Matches\n");
break;
case PCRE_ERROR_PARTIAL:
printf("Partial Match\n");
break;
case 0:
printf("Perfect Match\n");
break;
default:
printf("Error Code: %d\n",retexec);
break;
}
}
} else {
printf("Error in Regex Compilation");
}
}


Output here:

[root@localhost 21Aug2007]# ./nkans.out
Enter the details you wish to match:thi
Partial Match
Enter the details you wish to match:thing
Partial Match
Enter the details you wish to match:thingal
Perfect Match
Enter the details you wish to match:fldjlsjfl
No Matches
Enter the details you wish to match:

Google Code checkout:

svn co http://codeoftheday.googlecode.com/svn/trunk/21Aug2007

No comments: