Input validation in C

Posted on May 6, 2009. Filed under: Programming, Software | Tags: , , |

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(&regc, regex, 0);

 /* Does it match ? */
 return regexec(&regc, "800x500", 0, 0, 0) == 0;
}

Make a Comment

Make a Comment: ( 1 so far )

blockquote and a tags work here.

One Response to “Input validation in C”

RSS Feed for Brain Dump Comments RSS Feed

Regular expressions rock.


Where's The Comment Form?

  • Feed

  • Ohloh

  • Bookmarks

  • Categories

  • Visitors


  • Hits

    • 21,512 hits

Liked it here?
Why not try sites on the blogroll...