Search code examples
cregexposix

regular expression doesnt work while execute in c


i am trying to build regular expression with the regex.h lib.

i checked my expression in https://regex101.com/ with the the input "00001206 ffffff00 00200800 00001044" and i checked it in python as well, both gave me the expected result. when i ran the code below in c (over unix) i got "no match" print. any one have any suggest?

regex_t regex;
int reti;
reti = regcomp(&regex, "([0-9a-fA-F]{8}( |$))+$", 0);
if (reti) 
{
    fprintf(stderr, "Could not compile regex\n");
    exit(1);
}

reti = regexec(&regex, "00001206 ffffff00 00200800 00001044", 0, NULL, 0);
if (!reti) 
{
     printf("Match");
 }
  else if (reti == REG_NOMATCH) {
  printf("No match bla bla\n");
   }  

Solution

  • Your pattern contains a $ anchor, capturing groups with (...) and the interval quantifier {m,n}, so you need to pass REG_EXTENDED to the regex compile method:

    regex_t regex;
    int reti;
    reti = regcomp(&regex, "([0-9a-fA-F]{8}( |$))+$", REG_EXTENDED); // <-- See here
    if (reti) 
    {
        fprintf(stderr, "Could not compile regex\n");
        exit(1);
    }
    
    reti = regexec(&regex, "00001206 ffffff00 00200800 00001044", 0, NULL, 0);
    if (!reti) 
    {
        printf("Match");
    }
    else if (reti == REG_NOMATCH) {
        printf("No match bla bla\n");
    }  
    

    See the online C demo printing Match.

    However, I believe you need to match the entire string, and disallow whitespace at the end, so probably

    reti = regcomp(&regex, "^[0-9a-fA-F]{8}( [0-9a-fA-F]{8})*$", REG_EXTENDED);
    

    will be more precise as it will not allow any arbitrary text in front and won't allow a trailing space.