tags:

views:

412

answers:

5

Hello,

Doing regex in C# or PHP is very easy for me now. However currently I have a need to use regex in C. And, I don't seem to understand the usage of regcomp or regexec fully. It's definitely because of my lack of experience in C.

Any help and examples would be much appreciated!

+7  A: 

Use the PCRE library. Examples are included in the source, in the demo/ directory. Here's a direct link to pcredemo.c.

John Millikin
A perl compatible regex library - isn't that against the human rights act?
Martin Beckett
PCRE is pretty much a standard, and that makes it much easier for writers and maintainers dealing with the regular expressions.
strager
And... all I need is an example of PCRE usage in C... TT
Dave
@Dave: Examples are included in the PCRE distribution. Look in the `demo/` directory.
John Millikin
Yup thanks, I was just looking at that too. It has very good example as well!
Dave
+2  A: 

You need a library that provides it, and there are several to choose from. PCRE is one.

Dirk Eddelbuettel
To John and Dirk, I have installed PCRE already but I guess I'm interested in its usage in C.
Dave
A: 

The gnu C library has a regex library

Martin Beckett
Yes, and I couldn't figure out how to use it... namely the regcomp and regexec functions
Dave
+4  A: 

This may get you started, as you indicate regex(3) functions. Following is a trivial program matching its arguments. However, if you're relatively new to C, you'll want to go slowly with regex(3), as you'll be working with pointers and arrays and regmatch_t-supplied offsets and lions and tigers and bears. ;)

$ ./regexec '[[:digit:]]'   56789  alpha  "   "  foo12bar
matched: 56789
matched: foo12bar
$ ./regexec '[[:digit:]](foo'
error: Unmatched ( or \(
$ ./regexec '['
error: Invalid regular expression

... and the source:

#include <sys/types.h>
#include <regex.h>
#include <stdio.h>

int main(int argc, char **argv) {
  int r;
  regex_t reg;

  ++argv;  /* Danger! */

  if (r = regcomp(&reg, *argv, REG_NOSUB|REG_EXTENDED)) {
    char errbuf[1024];
    regerror(r, &reg, errbuf, sizeof(errbuf));
    printf("error: %s\n", errbuf);
    return 1;
  }

  for (++argv; *argv; ++argv) {
    if (regexec(&reg, *argv, 0, NULL, 0) == REG_NOMATCH)
      continue;
    printf("matched: %s\n", *argv);
  }

  return 0;
}
pilcrow
Perfect thanks you!
Dave
Also for anyone else looking at this, John Millikin's answer is just as good. His provided example is for PCRE and pilcrow's is for GNU C Lib's regex I believe.
Dave
A: 

There's also libslack(str) - string module:

http://libslack.org/manpages/str.3.html

ceeit