Mail Archives: djgpp/1997/09/09/17:50:57
From: | mauch AT uni-duisburg DOT de (Michael Mauch)
|
Newsgroups: | comp.os.msdos.djgpp
|
Subject: | DJGPP regex - how does it work?
|
Date: | Fri, 05 Sep 1997 00:34:28 +0200
|
Organization: | Home, sweet home (via Gesamthochschule Duisburg)
|
Lines: | 124
|
Message-ID: | <5und1g$l9o$2@news-hrz.uni-duisburg.de>
|
NNTP-Posting-Host: | ppp69.uni-duisburg.de
|
Mime-Version: | 1.0
|
To: | djgpp AT delorie DOT com
|
DJ-Gateway: | from newsgroup comp.os.msdos.djgpp
|
Hi!
I tried to use the functions regcomp() and regexec() from DJGPP's
regex.h, but obviously I'm plain too dumb to get these things to work.
Does anybody have a simple, working example how to use regex.h?
I include my test program below. It always prints "Matching", even if I
match the RE "a" against the string "b". If I supply an invalid regular
expression such as "a[" - then regcomp() works as expected (i.e. it
fails) and regerror() tells me where the problem is.
BTW: Searching for an example program using "regex.h", I found the file
DJGPP\TESTS\LIBC\POSIX\REGEX\r1.c which seems to be rather
incomplete/broken - is this only on my machine or is there another
secret behind it? On my machine it looks like this:
// DJGPP\TESTS\LIBC\POSIX\REGEX\r1.c
#include <stdio.h>
#include <regex.h>
int
main(int argc, char **argv)
{
rexec_
regcomp("a.*x"
}
Now, following is my test program. I'd be grateful if somebody could
look through it and tell me where I went wrong.
Thanks in advance...
Michael
// RegTest.c
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <sys/types.h>
#include <regex.h>
int Usage(void)
{
fprintf(stderr,"\nUsage: regtest expr string\n\n"
"Returns 0 if string matches the extended RE expr, "
"1 otherwise, "
"2 for errors.\n"
);
return 2;
}
void Error(int exit_code,char* format,...)
{
va_list arg;
va_start(arg, format);
fprintf(stderr,"\nError: ");
vfprintf(stderr, format, arg);
fprintf(stderr,"\n");
va_end(arg);
exit(exit_code);
}
char* RegError(int r,regex_t* preg)
/*
Returns the human-readable regex error string
in a dynamically allocated array.
The caller must free() this array.
*/
{
char* pBuf;
size_t BufLen;
BufLen = regerror(r,preg,NULL,0);
pBuf = (char*)malloc(BufLen);
regerror(r,preg,pBuf,BufLen);
return pBuf;
}
int main(int argc,char* argv[])
{
char* strRegex, *strString;
int r;
regex_t regex;
int cFlags = REG_NOSUB | REG_EXTENDED; // flags for regcomp()
int eFlags = 0; // flags for regexec()
regmatch_t pMatch[1];
if(argc<3)
return Usage();
strRegex = argv[1];
strString = argv[2];
r = regcomp(®ex,strRegex,cFlags);
if(r)
Error(2,"regcomp() says: %s\n",RegError(r,®ex));
r = regexec(®ex,strRegex,1,pMatch,eFlags | REG_TRACE);
// The following line didn't work as well:
// r = regexec(®ex,strRegex,0,NULL,eFlags);
if(!r)
{
printf("Matching.\n");
return 0; // found
}
else if(REG_NOMATCH == r)
{
printf("No match.\n");
return 1; // not found
}
else
Error(2,"regexec() says: %s\n",RegError(r,®ex));
return 2;
}
- Raw text -