Regular Expressions
By Brian W. Kernighan and Rob Pike, April 01, 1999
Regular expressions, one of the most broadly applicable of programmer's tools, provide a compact and expressive notation for describing patterns of text. They are also algorithmically interesting, easy to implement, and highly useful. Brian and Rob, who are researchers at Bell Labs and the authors of The Practice of Programming, present a compact implementation of grep that uses regular expressions.
Apr99: Regular Expressions
/* grep: search for re in file */
int grep(char *re, FILE *f, char *name)
{
int n, nmatch;
char buf[BUFSIZ];
nmatch = 0;
while (fgets(buf, sizeof buf, f) != NULL) {
n = strlen(buf);
if (n > 0 && buf[n-1] == '\n')
buf[n-1] = '\0';
if (match(re, buf)) {
nmatch++;
if (name != NULL)
printf("%s:", name);
printf("%s\n", buf);
}
}
return nmatch;
}
Example 5: The function grep scans a single file, calling match on each line.
Copyright © 1999, Dr. Dobb's Journal