简体   繁体   中英

Issues with regular expression rejecting string

regex_t regex;
int reti;
char msgbuf[100];

/* Compile regular expression, if two vowels it should be ok */
reti = regcomp(&regex, "[aoueiy].{2}", 0);
if (reti){
   fprintf(stderr, "Could not compile regex\n");
   exit(1);
}

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

I am trying to write an expression that is supposed to accept an string that contains at least two vowels. Here is my code so far, the string ao gives me "No match". I am new to regex and I find the manual hard to use. Very thankful for any help or tips.

Your regular expression matches a vowel followed by 2 other characters. [aoueiy] matches a vowel, . matches any characters, and adding {2} after it makes it match two characters. ao only has 1 character after the vowel, so it doesn't match.

The correct regexp is [aoueiy].*[aoueiy] . This matches two vowels with any number of characters (including 0) between them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM