Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use regular expressions in C?

Tags:

c

regex

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 can't find any straight forward examples (i.e., "use this library", "this is the methodology").

Can someone give me a simple example?

like image 456
jeffkolez Avatar asked Oct 27 '09 15:10

jeffkolez


1 Answers

You can use PCRE:

The PCRE library is a set of functions that implement regular expression pattern matching using the same syntax and semantics as Perl 5. PCRE has its own native API, as well as a set of wrapper functions that correspond to the POSIX regular expression API. The PCRE library is free, even for building commercial software.

See pcredemo.c for a PCRE example.

If you cannot use PCRE, POSIX regular expression support is probably available on your system (as @tinkertim pointed out). For Windows, you can use the gnuwin Regex for Windows package.

The regcomp documentation includes the following example:

#include <regex.h>

/*
 * Match string against the extended regular expression in
 * pattern, treating errors as no match.
 *
 * Return 1 for match, 0 for no match.
 */

int
match(const char *string, char *pattern)
{
    int    status;
    regex_t    re;

    if (regcomp(&re, pattern, REG_EXTENDED|REG_NOSUB) != 0) {
        return(0);      /* Report error. */
    }
    status = regexec(&re, string, (size_t) 0, NULL, 0);
    regfree(&re);
    if (status != 0) {
        return(0);      /* Report error. */
    }
    return(1);
}
like image 145
Sinan Ünür Avatar answered Oct 06 '22 23:10

Sinan Ünür