I have problem. The user types a command, which is stored in the cmd variable. The first four characters in the command are non-variable. I retrieve all characters starting from the fourth one. The retrieved characters are passed to the variable check.
This is where the biggest problem arises. I would like to make it so that the program checks for a valid string. The only valid string is |3| but there can be many such strings, for example |4|30| or |15|1|100| and so on to infinity. The most important thing is that the user between two | characters can only enter numbers in decimal format.
I have created a regex, but it doesn't work because even the decimal number alone without the | characters gives a positive result. For there to be a positive result there must be two | characters and a decimal number between them. How can I make the program work properly?
#include "stdarg.h"
#include "string.h"
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <regex.h>
int main()
{
char cmd[] = "WBRA|5|80|120|3|40|";
int length = strlen(cmd);
char check[100];
int index = 0;
for(int i=4; i<length; i ){
check[index ] = cmd[i];
}
printf("%s\n\r", check);
regex_t regex;
int return_value;
return_value = regcomp(®ex,"(\\|\\d*\\|){n}",0);
return_value = regexec(®ex, "check", 0, NULL, 0);
printf("Result %d\n\r", return_value); // 0 is correct
}
CodePudding user response:
You need to change the two lines in your code to
return_value = regcomp(®ex,"^\\|([0-9] \\|) $",REG_EXTENDED);
return_value = regexec(®ex, check, 0, NULL, 0);
See the C demo.
Details:
- The regex must be
^\|([0-9] \|) $
that matches a whole string that starts with a|
char and then contains one or more occurrences of one or more digits and a|
char till the end REG_EXTENDED
is required for this pattern to work correctly- You used
"check"
rather thancheck
in theregexec
command (so you were checking the regex againstcheck
word and not the|5|80|120|3|40|
string).