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(®ex, "1 | 2c | 3c", reg_extended); if( reti ){ fprintf(stderr, "could not compile regex\n"); return(1); } /* execute regular expression */ reti = regexec(®ex, "123", 0, null, 0); if( !reti ){ puts("match"); } else if( reti == reg_nomatch ){ puts("no match"); } else{ regerror(reti, ®ex, msgbuf, sizeof(msgbuf)); fprintf(stderr, "regex match failed: %s\n", msgbuf); return 1; } /* free compiled regular expression if want use regex_t again */ regfree(®ex); 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
Post a Comment