简体   繁体   中英

Curley braces are not working in regular expression in C language

The Curly braces{} are not working in C language Regular expressions, it is always giving output as NO match , if i give correct input as "ab" or "ac". I would request to help in this case.

 #include <sys/types.h>
  #include <regex.h>
  #include <stdio.h>


   int main(int argc, char *argv[]){ regex_t regex;
        int reti;
        char msgbuf[100];

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

        /* Execute regular expression */
        reti = regexec(&regex, "ab", 0, NULL, 0);
        if( !reti ){
                puts("Match");
        }
        else if( reti == REG_NOMATCH ){
                puts("No match");
        }
        else{
                regerror(reti, &regex, msgbuf, sizeof(msgbuf));
                fprintf(stderr, "Regex match failed: %s\n", msgbuf);
                return 1;
        }

       /* Free compiled regular expression if you want to use the regex_t again */
        regfree(&regex);

        return 0;
}

You are using the Basic Regular Expressions dialect that has no knowledge of the quantifier {n} in the regex.

One solution would be to supply the option REG_EXTENDED as the last argument instead of 0 when creating your regex_t object.

reti = regcomp(&regex, "[a-c]{2}", REG_EXTENDED);

See http://ideone.com/oIBXxu for a Demo of your code with my modification.


As Casimir et Hippolyte notes in the comments Basic Regular Expressions support the {} quantifier as well but the curly braces must be escaped with a \\ in the regex which again has to be escaped in the C string as \\\\ . So you can use the line

reti = regcomp(&regex, "[a-c]\\{2\\}", 0);

as well as an alternative to the solution above(running Demo with this line modified under http://ideone.com/x7vlIO ).

You can check http://www.regular-expressions.info/posix.html for more information about the difference between Basic and Extended Regular Expressions.

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