Regexp for a double

/^[0-9]+.[0-9]+$ : use this for doubles.

accepts 123.123 types.


the regexp above is not perfect since it accepts "09" which is not a valid number. a better expression would be:

"^(-?)(0|([1-9][0-9]*))(\\.[0-9]+)?$"

where:

1. is an optional negative sign;
2. is zero or a valid non-zero integer;
4. is the optional fracture part;

in theory, the fracture part should be written as "(\.[0-9]*[1-9])?" instead, because a number must not have tailing zeroes. in practice, the source string might have been created with a fixed number of digits e.g:

printf("%.1f", x);

so it might easily end with a zero character. and, of course, these are all fixed point representations, not the doubles themselves. a double number can be written as -1.23e-4 as well instead of -0.000123.


There's nothing wrong with the regex per se, it's your escaping that's at fault. You need to double escape the \ character since that's also a C++ string escape character.

Additionaly there is an edge case where this regex would think that 1. is a valid floating pointer number. So you might be better off with /^[0-9]+(\\.[0-9]+)?$ which eliminates that possibility.

Tags:

Regex

C++ Cli