Reputation: 336
I am trying to match a valid nickname in C.
I have the following function:
int check_valid_nickname(char *nick) {
if(!match(nick,NICK_PATTERN)) {
return 0;
} else {
}
int match(char *str, char *pattern) {
int status;
regex_t re;
if (regcomp(&re, pattern, REG_EXTENDED|REG_NOSUB) != 0) {
/* Report error. */
return 0;
}
status = regexec(&re, str, (size_t) 0, NULL, 0);
regfree(&re);
if (status != 0) {
/* Report error. */
return 0;
}
return 1;
}
and NICK_PATTERN is defined as
#define NICK_PATTERN "/^[a-z0-9_\\|\\{\\}\\[\\]\\^]{4,36}$/i"
I have tested the pattern on regexr and it matches perfectly the way I need it.
However, my function in C is still always returning 0. Am I overlooking something? Thanks for any pointers.
Upvotes: 0
Views: 316
Reputation: 44063
The regex you're looking for is
#define NICK_PATTERN "^[]a-z0-9|{}^[]{4,36}$"
and you want to compile it like so:
regcomp(&re, pattern, REG_ICASE | REG_EXTENDED | REG_NOSUB)
regcomp
, regexec
etc. use the POSIX regular expression syntax, which means slightly different escaping rules, no slashes for matching, and no flags like in Perl -- these are replaced, in a manner of speaking, by the functions and their flags. There's a rundown of POSIX syntax here. It is written for a C++ interface, but the rules are the same.
Differences from what you expected in this particular case: You don't have to escape in a []
set, and if there's a ]
to be part of the set, it has to come at the front.
Upvotes: 1