c - tester - regular expression tutorial




c regular expression howto (3)

It's been 10 years since I looked at c. I need to write a little program in c that parses a string. I wanted to use regular expressions since I've been using them for years, but I have no idea how to do that in c. I've spent the morning Googling and I can't find any straight forward examples (ie. use this library, this is the methodology). Can someone give me a simple example?

Thanks!


Another option besides a native C library is to use an interface to another language like Python or Perl. Not having to deal with C's string handling, and the better language support for regex's should make things much easier for you. You can also use a tool like SWIG to generate wrappers for calling the code from C.


If forced into POSIX only (no pcre), here's a tidbit of fall back:

#include <regex.h>
#include <stdbool.h>

bool reg_matches(const char *str, const char *pattern)
{
    regex_t re;
    int ret;

    if (regcomp(&re, pattern, REG_EXTENDED) != 0)
        return false;

    ret = regexec(&re, str, (size_t) 0, NULL, 0);
    regfree(&re);

    if (ret == 0)
        return true;

    return false;
}

You might call it like this:

int main(void)
{
   static const char *pattern = "/foo/[0-9]+$";

   /* Going to return 1 always, since pattern wants the last part of the
    * path to be an unsigned integer */
   if (! reg_matches("/foo/abc", pattern))
       return 1;

   return 0;
}

I highly recommend making use of PCRE if its available. But, its nice to check for it and have some sort of fall back.

I pulled the snippets from a project currently in my editor. Its just a very basic example, but gives you types and functions to look up should you need them. This answer more or less augments Sinan's answer.


You should also take a look to the regex library. It uses regular expressions like the ones you can write into the Linux Shell.

For more informations, under Linux, type "man regcomp" without quotes







regex