From Coding Horror:
Some people, when confronted with a problem, think "I know, I'll use
regular expressions." Now they have
two problems.
What I mean is: are you sure a regular expression is the best way to solve your problem? Maybe you can test whether the string is a URL with some more lightweigth method?
Edit
The following program on my computer, with output redirected to /dev/null
, prints (to stderr
)
rx time: 1.730000
lw time: 0.920000
Program Listing:
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <regex.h>
#include <string.h>
#include <time.h>
int goodurl_rx(const char *buf) {
static regex_t rx;
static int done = 0;
int e;
if (!done) {
done = 1;
if ((e = regcomp(&rx, "^www\\.[a-z][a-z0-9]*\\.(com|edu|org)$", REG_EXTENDED)) != 0) {
printf("Error %d compiling regular expression.\n", e);
exit(EXIT_FAILURE);
}
}
return !regexec(&rx, buf, 0, NULL, 0);
}
int goodurl_lw(const char *buf) {
if (*buf++ != 'w') return 0;
if (*buf++ != 'w') return 0;
if (*buf++ != 'w') return 0;
if (*buf++ != '.') return 0;
if (!isalpha((unsigned char)*buf++)) return 0;
while (isalnum((unsigned char)*buf)) buf++;
if (*buf++ != '.') return 0;
if ((*buf == 'c') && (*(buf+1) == 'o') && (*(buf+2) == 'm') && (*(buf+3) == 0)) return 1;
if ((*buf == 'e') && (*(buf+1) == 'd') && (*(buf+2) == 'u') && (*(buf+3) == 0)) return 1;
if ((*buf == 'o') && (*(buf+1) == 'r') && (*(buf+2) == 'g') && (*(buf+3) == 0)) return 1;
return 0;
}
int main(void) {
clock_t t0, t1, t2;
char *buf[] = {"www.alphanumerics.com", "ww2.alphanumerics.com", "www.alphanumerics.net"};
int times;
t0 = clock();
times = 1000000;
while (times--) {
printf(" %s: %s\n", buf[0], goodurl_rx(buf[0])?"pass":"invalid");
printf(" %s: %s\n", buf[1], goodurl_rx(buf[1])?"pass":"invalid");
printf(" %s: %s\n", buf[2], goodurl_rx(buf[2])?"pass":"invalid");
};
t1 = clock();
times = 1000000;
while (times--) {
printf(" %s: %s\n", buf[0], goodurl_lw(buf[0])?"pass":"invalid");
printf(" %s: %s\n", buf[1], goodurl_lw(buf[1])?"pass":"invalid");
printf(" %s: %s\n", buf[2], goodurl_lw(buf[2])?"pass":"invalid");
} while (0);
t2 = clock();
fprintf(stderr, "rx time: %f\n", (double)(t1-t0)/CLOCKS_PER_SEC);
fprintf(stderr, "lw time: %f\n", (double)(t2-t1)/CLOCKS_PER_SEC);
return 0;
}