Friday, December 21, 2012

Regular expression to parse a double number

Here is the simple example of how to validate your input is really a double value. But first here is a king of WRONG regexp: \d+.\d+ and variants of this example. Whats wrong with this expression. Well, it

- DOES NOT match the sign (positive or negative)
- Requires obligatary dot character
- Requires obigatory digits after dot

Now here is the PROPER expression: ^[\+\-]{0,1}([ 0-9]+\.){0,1}[ 0-9]+$

- You may or may not set the sign before a number
- You may parse values like these: 100, 100.0, 0.11, +1, -3000, -1.2
- This expression makes you sure the string contains at least one digit

However such the expression does not support parsing the values like 1.23e-10 etc, but it can e simply extended to support such ones.