Regex in C, check if string contains specific characters

时间:2016-09-29 23:36:13

标签: c regex

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.

1 个答案:

答案 0 :(得分:2)

如果您的正则表达式引擎支持它:

"-[sh]+$"

否则:

"-[sh][sh]*$"
相关问题