2

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");
   }  
0

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

thanks dude, i have one more Q, i am reading this data from file but when i am trying to read i get no match.how can i check if there is any other invisible characters ?
@YonatanAmir I am really certain this is not related to the regex. Please check how to read Unicode files in C. It might be related to BOM. Make sure you do not keep it when passing the contents to the regex engine.
sorry for the spam it was '\n'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.