Issue with setting a correct regular expression in C using regex

Viewed 51

I'd like to match all strings that begin with a set of characters a-z, then exactly one : and another set of characters a-z right after that.

So as an example, the string "an:example" would be a correct match.

And another example, "another:ex:ample" needs to be a mismatch.

I have tried to set it up like that but it matches everything, even if i take bad string as input :(

So my regular expression is "[a-z]:[a-z]" but it evaluates the string "1an:example" as a Match :/

How can I do this correctly?

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

int main() {
   regex_t regex;
   int retis;
   char* str = "1an:example";
   
   retis = regcomp(&regex, "[a-z]:[a-z]", 0);
   retis = regexec(&regex, str, 0, NULL, 0);
   
   if(!retis) {
      puts("Match");
   }
   else if(retis == REG_NOMATCH) {
      puts("No match");
   }
   
   regfree(&regex);
   return 0;
}
1 Answers

You need

retis = regcomp(&regex, "^[a-z]+:[a-z]+$", REG_EXTENDED);

See the C online demo.

That is:

  • ^ (start of string) and $ (end of string) are anchors that require the regex to match the whole string
  • [a-z]+ matches one or more lowercase letters
  • REG_EXTENDED allows extended regex syntax, e.g. in regex.h it is required to enable the $ anchor.
Related