IgorD
IgorD

Reputation: 183

Regex fails in C, online tests pass

A regex that should work fails when I use it in C.

When I paste this regex here - https://regex101.com and test it it seems fine, as expected.

//clang 3.8.0

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

int main(void)
{
   char    *regPatt = regPatt = "^HR(\\d{2})$";
   regex_t  regex;
   short    retval = regcomp (&regex, regPatt, 0);
   short    status = regexec (&regex, "HR16", (size_t) 0, NULL, 0);

   printf ("%hd", status);

   regfree (&regex);
}

So, online test work just fine.

Regex - ^HR(\d{2})$

String - HR16

At https://regex101.com for example, all is fine, I get a match.

In my code, it fails. Value printed with printf() is 1 (REG_NOMATCH).

edit - the code can be pasted for a test here: https://rextester.com/l/c_online_compiler_gcc

Upvotes: 2

Views: 325

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627082

You should use [0-9] instead of \d and pass REG_EXTENDED to the regcomp function.

REG_EXTENDED
Use POSIX Extended Regular Expression syntax when interpreting regex. If not set, POSIX Basic Regular Expression syntax is used.

Here is the updated code:

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

int main(void)
{
   char    *regPatt = regPatt = "^HR([0-9]{2})$";
   regex_t  regex;
   short    retval = regcomp (&regex, regPatt, REG_EXTENDED);
   short    status = regexec (&regex, "HR16", (size_t) 0, NULL, 0);
   printf ("%hd", status);
   regfree (&regex);
}

Upvotes: 7

Related Questions