Reputation: 168
I'm writing a parser that analyze the content passed in parameter and compare to a regex. This parser should return boolean if found a structure of variable :
int a;
double abc;
char test;
Those variables should match but not...
Here is my code, I thought my regex is true..
#include "includes.h"
int check_match_var(char *str)
{
int err;
int match;
regex_t preg;
char err_buf[BUFSIZ];
const char *regex = "/^(int|char|float|double) [a-zA-Z0-9]{1,};/";
err = regcomp(&preg, regex, 0);
printf("Err : %d\n", err);
if (err == 0)
{
match = regexec(&preg, str, 0, NULL, 0);
regfree(&preg);
if (match == 0)
printf("Match !\n");
else
printf("No match !\n");
}
else
{
regerror(err, &preg, err_buf, BUFSIZ);
printf("regcomp: %s\n", err_buf);
return (1);
}
return (0);
}
int marvin(char **av)
{
check_match_var(av[1]);
return (0);
}
int main(int ac, char **av)
{
if (ac == 2)
{
marvin(av);
}
else
printf("\n");
return (0);
}
Anyway it return 1 (no match), I want it return 0 (match)..
Includes file :
#ifndef INCLUDES_H_
#define INCLUDES_H_
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <regex.h>
#endif
Thanks for help
Upvotes: 1
Views: 342
Reputation: 753475
The code is using the POSIX regular expression code from <regex.h>
. You can find the information about regcomp()
and regexec()
online.
There are two problems with the code posted:
Paul Roub correctly identified that the slashes in the regex string are not required.
Jonathan Leffler correctly identified that the regular expressions processed by regcomp()
and regexec()
are 'basic regular expressions' or BRE, but the notation is trying to use 'extended regular expressions' or ERE. And the way to request ERE support is via the REG_EXTENDED
flag as one of the flags in the third argument to regcomp()
.
In a comment, user3486006 confirms that both changes (and adding REG_NOSUB
to the regcomp()
) means that it works. See the manual page for what REG_NOSUB
does; the match would have worked with or without the flag, but adding the flag is sensible in this context.
Community Wiki answer: if Paul posts an answer, accept it, please.
Upvotes: 2