Weird blank character behaviour in regex C -
i have problem using regex in c. want collect command (get, put or del) , filepath, send right command server.
if compile ' [[:blank:]]*(get|put|del|help) '
, code works , collect right thing. however, when add expression, such : '[[:blank:]]*(get|put|del|help)[[:blank:]]+([a-z])'
, regexec returns reg_nomatch.
do have solution or know why?
this code:
#include <regex.h> #include "dgb.h" #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <stdio_ext.h> define mode "client" int main(int argc, char *argv[]) { regex_t preg; const char *str_regex = "[[:blank:]]*(get|put|del|help)[[:blank:]]+([a-z])"; char str_request[51]; int reg_init; int reg_request; size_t nmatch = 0; regmatch_t *pmatch = null; reg_init = regcomp(&preg, str_regex, reg_icase); if (reg_init != 0) { printf("error\n"); exit(exit_failure); } nmatch = preg.re_nsub; pmatch = malloc(nmatch * sizeof(*pmatch)); checkmem(pmatch); while(strcmp(str_request,"quit") != 0) { printf(">>"); scanf("%50s", str_request); __fpurge(stdin); //fpurge on osx reg_request = regexec(&preg, str_request, nmatch, pmatch, 0); if (reg_request == reg_nomatch) { printf("%s: invalid command, please tap help\n", mode); } else if (reg_request == 0) { char *cmd = null; int start = pmatch[0].rm_so; int end = pmatch[0].rm_eo; size_t size = end - start; cmd = malloc (sizeof (char*) * (size + 1)); strncpy(cmd, &str_request[start], size); cmd[size] = '\0'; printf ("%s\n", cmd); free(cmd); } } free(pmatch); }
there 2 problems here:
format string
%s
inscanf
extracts string of non-whitespace characters , stops @ first whitespace character found. when inputget something
,get
readscanf
line.scanf("%50s", str_request);
one option change code use
fgets
read whole line of input. note new line character included in buffer, have deal accordingly.you writing regex in extended regular expression (ere) syntax, since using alternation
|
, grouping(
,)
, 1 or more quantifier+
.in basic regular expression (bre),
|
,+
not available, , parentheses must escaped\(
\)
invoke special meaning.therefore,
reg_extended
flag necessary make regex works intended.
Comments
Post a Comment