Reputation: 111
I try to research for REGEX in C and try to understand but I have trouble with pattern of the string type. In this program I want to verify string input is a number(only digits number, not characters, space, or special characters)
#include<stdio.h>
#include <regex.h>
void print_result(int return_value){
if (return_value == 0){
printf("Pattern found.\n");
}
else if (return_value == REG_NOMATCH){
printf("Pattern not found.\n");
}
else{
printf("An error occured.\n");
}
}
int main() {
regex_t regex;
int return_value;
int return_value2;
return_value = regcomp(®ex,"[^a-fA-F_][0-9]+",0);
return_value = regexec(®ex, "4324", 0, NULL, 0);
return_value2 = regcomp(®ex,"\d+",0);
return_value = regexec(®ex, "4324", 0, NULL, 0);
print_result(return_value); //not found
print_result(return_value); //no found
print_result(return_value2);
return 0;
}
Can you give me some ideas to verify the input. I want find another way without use ASCII values
Upvotes: 0
Views: 54
Reputation: 241901
If you specify the flags as 0 in regcomp
:
return_value = regcomp(®ex,"[^a-fA-F_][0-9]+",0);
then you are accepting the default regex syntax, which is a so-called Basic Regular Expression (BRE). The only sensible thing that can be said about BREs is "don't use them." Always specify the REG_EXTENDED
flag (at least), and then you will be working with a regular expression syntax that at least bears a passing resemblance to what you expect. (Otherwise, your strings will be dominated by what's technically called "leaning timber": \
characters which enable metacharacters in the regex, and more \
characters so that the \
characters you need are not treated as escape characters in the character string.)
Take a look at man regexec and man 7 regex for more details. Make sure you read the second link thoroughly (although you can ignore basic regular expression syntax :-) ) because there are many commonly-used syntaxes in more modern regex libraries which are not present in Posix regexes, not even extended ones. (That includes \d
, used in your second regex. Posix has named character classes, such as [[:digit:]]
.)
Upvotes: 2