[LCP]sample code for matching regexp

Roberto Diaz rdiazmartin at vivaldi.dhis.org
Tue Sep 11 07:49:04 UTC 2001


The only thing you need to know are posix (or extended) regular
expressions.. for example:

#include <stdio.h>
#include <stdlib.h>
#include <regex.h>

char errbuf[255];

int
main (int argc, char *argv[])
{
  regex_t reg; /* our regular expression */
  int rst;

  if (argc != 3) {
    fprintf (stderr, "usage: regexp <regexp> <string>\n");
    exit (EXIT_FAILURE);
  }
  /* first we compile the expression */
  if ((rst = regcomp (&reg, argv[1], REG_NOSUB)) != 0) {
    regerror (rst, &reg, errbuf, 255);
    fprintf (stderr, "%s", errbuf);
    exit (EXIT_FAILURE);  
  }
  /* we try to match */
  if ((rst = regexec (&reg, argv[2], 0, NULL, 0)) == REG_NOMATCH) {
    fprintf (stdout, "matched failed\n");
    exit (EXIT_SUCCESS);
  }
  
  regfree (&reg);
  /* the expression has matched */
  fprintf (stdout, "it has matched\n");
 
  exit (EXIT_SUCCESS);
}

You have to do the following:

	* compile the expression regcomp(3) (this only prepares a struct)
	* run the expression regexec(3)
	* free the expression regfree(3)

In the above example I havent used all the information you can
collect.. if you could be more specific in your question we could help you
much more.

> Hello Everybody
> I am trying to use the GNU C library
> for matching regular epressions.
> I have been refering to the man pages of help.
> But i would like to go thru some sample
> codes where regular expression matching functions
> have been used .
> I haven't been able to find any yet.
> Any help in this regard will be
> appreciated.

---
Roberto Diaz <rdiazmartin at vivaldi.dhis.org>
..For a Brave GNU World..    
                                        Concerto Grosso Op. 3/8 A minor
                        Antonio Vivaldi (so... do you need beautiful words?)
                                                                      -----




More information about the linuxCprogramming mailing list