1

Using this code, i created a function that take a string and check if it correspond to a roman number(inspiring myself from this thread)

int checkregex(char *in){
regex_t regex;
char *expression="^M{0,4}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$";
int reti;
char msgbuf[100];

/* Compile regular expression */
reti = regcomp(&regex, expression, 0);
if (reti) {
    fprintf(stderr, "Could not compile regex\n");
    exit(1);
}

/* Execute regular expression */
reti = regexec(&regex, in , 0, NULL, 0);
if (!reti) {
    printf("Match\n");
    return 1;
}
else if (reti == REG_NOMATCH) {
    printf("No match\n");
    return 0;
}
else {
    regerror(reti, &regex, msgbuf, sizeof(msgbuf));
    fprintf(stderr, "Regex match failed: %s\n", msgbuf);
    exit(1);
}
return 0;

}

my problem is that it always return "No match", so i wonder if my regex is not compatible with POSIX, or if i miss something else...

could someone help me out ?

Community
  • 1
  • 1
secrav
  • 13
  • 5

1 Answers1

3

You need to add REG_EXTENDED flag as you are using limiting quantifiers without escaping braces and start/end string anchors.

See the IDEONE demo:

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

int checkregex(char *in){
  regex_t regex;
  char *expression="^M{0,4}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$";
  int reti;
  char msgbuf[100];

  /* Compile regular expression */
  reti = regcomp(&regex, expression, REG_EXTENDED);
  if (reti) {
    fprintf(stderr, "Could not compile regex\n");
    return -1;
  }

  /* Execute regular expression */
  reti = regexec(&regex, in , 0, NULL, 0);
  if (!reti) {
    printf("Match\n");
    return 1;
  }
  else if (reti == REG_NOMATCH) {
    printf("No match\n");
    return 0;
  }
  else {
    regerror(reti, &regex, msgbuf, sizeof(msgbuf));
    fprintf(stderr, "Regex match failed: %s\n", msgbuf);
    exit(1);
  }
  return 0;
}

int main(void) { 
    int x = checkregex("XII");
    printf("%d\n", x);
    return 0;
}
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563