regex - | (or operator is not working in the regular expression in C language) -


the or operator (|) not working in c language regular expressions, giving output match , if give incorrect input "12" or "123" or c displaying match. request in 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, "1 | 2c | 3c", reg_extended);     if( reti ){ fprintf(stderr, "could not compile regex\n"); return(1); }      /* execute regular expression */     reti = regexec(&regex, "123", 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 want use regex_t again */     regfree(&regex);      return 0; 

}

your regex 1 | 2c | 3c matches 1 in i have 1 dollar, comments see need match whole strings, not part of them. that, need use anchors ^ (start of string) , $ (end of string) work when use reg_extended flag.

when use alternatives, need either repeat anchors, or set group of parentheses:

^1$|^2c$|^3c$ 

or

^(1|2c|3c)$ 

these expressions will safely match whole strings 1, 2c, or 3c.


Comments

Popular posts from this blog

Magento/PHP - Get phones on all members in a customer group -

php - .htaccess mod_rewrite for dynamic url which has domain names -

Website Login Issue developed in magento -