Synor Synor - 2 months ago 8
C Question

Regex in C, check if string contains specific characters

I want to have a regex that contains one and only one "-", followed by "s" or "h".
So, "-shshshshs" would match, "-ssssss" would too, but "-so" would not match, neither would "sh".

So far, I only succeeded to match "if strings contains "-" and "s" or "h", but typing "-sho" is accepted.

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

/* Execute regular expression */
reti = regexec(&regex, "--sh", 0, NULL, 0);
if (!reti) {
puts("Match");
} else {
puts("No match");
}


Thanks in advance.

Answer

If your regex engine supports it:

"-[sh]+$"

Otherwise:

"-[sh][sh]*$"