dhilst

regex example


/*
* File: regex.c
*
* This is a sample regex usage, gets three arguments. It is a grep
* like tool.
* -f <FILE> -> A file to be read if omited or - stdin is read
* -p <PATTERN> -> The pattern to be matched agains every line on FILE
* -v -> Invert the match, as like grep -v.
*
* Compiling: gcc -o preg regex.c
*/


#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <regex.h>
#include <unistd.h>
#include <getopt.h>



int main(int argc, char **argv)
{
regex_t reg;
char pattern[256];
int status;
char buf[256];
FILE *fp = NULL;
int opt;
int inverted = 0;

while ((opt = getopt(argc, argv, "vp:f:")) != -1) {
switch (opt) {
case 'v':
inverted = 1;
break;
case 'p':
strncpy(pattern, optarg, 256);
break;
case 'f':
if (optarg[0] == '-') {
fp = stdin;
} else {
fp = fopen(optarg, "r");
if (!fp) {
perror("fopen");
exit(EXIT_FAILURE);
}
}
break;
}
/* printf("%c\n", opt); */
}

if (!fp)
fp = stdin;

status = regcomp(&reg, pattern, REG_EXTENDED | REG_NOSUB);
if (status != 0)
{
fprintf(stderr, "Compiling the regular expression \"%s\" failed.\n", pattern);
exit(EXIT_FAILURE);
}


while (fgets(buf, 256, fp)) {
status = regexec(&reg, buf,
/* nmatch = */ 0,
/* pmatch = */ NULL,
/* eflags = */ 0);

if (inverted ? status : !status) {
printf("%s", buf);
}
}

return 0;
}