user4285359
user4285359

Reputation: 151

Regular Expressions are not returning correct solution

I'm writing a C program that uses a regular expressions to determine if certain words from a text that are being read from a file are valid or invalid. I've a attached the code that does my regular expression check. I used an online regex checker and based off of that it says my regex is correct. I'm not sure why else it would be wrong.
The regex should accept a string in either the format of AB1234 or ABC1234 ABCD1234.

//compile the regular expression
reti1 = regcomp(&regex1, "[A-Z]{2,4}\\d{4}", 0);
// does the actual regex test
status = regexec(&regex1,inputString,(size_t)0,NULL,0);

if (status==0)
    printf("Matched (0 => Yes):  %d\n\n",status);
else 
    printf(">>>NO MATCH<< \n\n");

Upvotes: 0

Views: 61

Answers (1)

Karl Reid
Karl Reid

Reputation: 2217

You are using POSIX regular expressions, from regex.h. These don't support the syntax you are using, which is PCRE format, and is much more common these days. You are better off trying to use a library that will give you PCRE support. If you have to use POSIX expressions, I think this will work:

#include <regex.h>
#include "stdio.h"
int main(void) {
  int status;
  int reti1;
  regex_t regex1;
  char * inputString = "ABCD1234";

  //compile the regular expression
  reti1 = regcomp(&regex1, "^[[:upper:]]{2,4}[[:digit:]]{4}$", REG_EXTENDED);
  // does the actual regex test
  status = regexec(&regex1,inputString,(size_t)0,NULL,0);

  if (status==0)
      printf("Matched (0 => Yes):  %d\n\n",status);
  else 
      printf(">>>NO MATCH<< \n\n");

  regfree (&regex1);
  return 0;
}

(Note that my C is extremely rusty, so this code is probably horrible.)

I found some good resources on this answer.

Upvotes: 1

Related Questions