arkdevelopment
arkdevelopment

Reputation: 167

Regex in C For Matching

I need to make a regex that can match any alphanumeric string of a length < 99 enclosed by two @. The first character after the '@' can also be '_' which I'm not sure how to account for. Ex. @U001@ would be valid. @_A111@ would also be valid. However, @____ABC@ would not be valid, and neither would @ABC.

I'm relatively new to regex and noticed that the \z is an unrecognized escape sequence. I'm trying to write it in C11 if that matters.

#include <regex.h>        
regex_t regex;
int reti;
char msgbuf[100];

/* Compile regular expression */
reti = regcomp(&regex, "^@[[:alnum:]]@\z", 0);
if (reti) {
    fprintf(stderr, "Could not compile regex\n");
    exit(1);
}

Upvotes: 0

Views: 2776

Answers (1)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 522635

Try using the following pattern:

^@[_[:alnum:]][:alnum:]{0,97}@

Here is a brief explanation of the pattern

^                from the start of the string
@                match @
[_[:alnum:]]     match underscore or alpha
[:alnum:]{0,97}  then match zero to 97 alpha
@                match @

Code:

reti = regcomp(&regex, "^@[_[:alnum:]][:alnum:]{0,97}@", 0);

Upvotes: 1

Related Questions