Reputation: 183
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 (®ex, regPatt, 0);
short status = regexec (®ex, "HR16", (size_t) 0, NULL, 0);
printf ("%hd", status);
regfree (®ex);
}
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
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 (®ex, regPatt, REG_EXTENDED);
short status = regexec (®ex, "HR16", (size_t) 0, NULL, 0);
printf ("%hd", status);
regfree (®ex);
}
Upvotes: 7