Reputation: 7593
I'm trying to check if a string is a valid number. A valid number is something like 123 or 123.456. I tried matching with [0-9]+(\\.[0-9]+)?
, but that's not working.
Here's what I have so far.
#include <stdio.h>
#include <regex.h>
int main()
{
const char* string = "123";
regex_t preg;
regcomp(&preg, "[0-9]+(\\.[0-9]+)?", 0);
if(regexec(&preg, string, (size_t)0, NULL, 0) == 0){
printf("valid number\n");
}
else{
printf("not valid number\n");
}
regfree(&preg);
return 0;
}
When I run this, it returns "not valid number".
This is part of a bigger program, I've just extracted the regex part to simplify my question.
Upvotes: 0
Views: 684
Reputation: 1
Read regcomp(3) & regex(7) man pages. You need the REG_EXTENDED
flag because you use ?
in your regexp.
int errcode = regcomp(&preg, "[0-9]+(\\.[0-9]+)?", REG_EXTENDED);
if (errcode) {
char errmsg[80];
memset (errmsg, 0, sizeof(errmsg));
regerror(errcode, &preg, errmsg, sizeof(errmsg));
fprintf(stderr, "regexp failure: %s\n", errmsg);
exit(EXIT_FAILURE);
}
However for your particular test strtod(3) might be enough (and it gives the number and the end pointer, so check that the end pointer points to the terminating null byte).
Upvotes: 4
Reputation: 6421
If you're trying to check if a string represents a number, you could do it by attempting a conversion to double
and seeing if it succeeds, obviating the need to use regexes at all. For example, the following program tests if a string can be converted to a number:
#include <stdlib.h>
int is_number(const char *s)
{
char *end;
(void)strtod(s, &end);
return end==s;
}
The only problem with this is that it will succeed if the beginning of the string can be converted. To test if the whole string is convertible, you'd have to do:
#include <string.h>
#include <stdlib.h>
int is_number(const char *s)
{
char *end;
(void)strtod(s, &end);
return end==s+strlen(s);
}
Or, alternatively:
#include <stdlib.h>
int is_number(const char *s)
{
char *end;
(void)strtod(s, &end);
return *end=='\0';
}
Upvotes: 1