Input validation in C
Just today I found a stable and powerful way to validate inputs in C, using regular expressions. Gnulib provides a header called regex.h and doing man regex.h will help you find more. Here’s how you use it.
First, the regular expression should be ‘compiled’ – not in the usual sense, but it’s converted to a format which increases the speed of pattern matching.
Here’s a simple example, which is used to validate rectangular dimension inputs.
#include <regex .h>
int main()
{
char *regex = "[1-9][0-9]\\{1,\\}x[1-9][0-9]\\{1,\\}";
regex_t regc;
regcomp(®c, regex, 0);
/* Does it match ? */
return regexec(®c, "800x500", 0, 0, 0) == 0;
}




Regular expressions rock.
Nelson
May 6, 2009