Search code examples
regexdecimalnegative-number

Regex decimal for negative number with formatting conditions


Dear gods of regex (http://xkcd.com/208/),

Please provide a pattern that matches decimal numbers up to 4 decimal places (I've included acceptable examples below) albeit with a couple extra conditions (listed at the bottom).

Acceptable:

0
0.1
0.12
0.123
0.1234
1
1.1
...
123456789.1234

(Note: the last example above is to indicate that there's no limit on how big the number can get)

Also acceptable are negative numbers:

-0.1
-0.12
-0.123
-0.1234
-1
-1.1
...
-123456789.1234

(Note: there's no limit on how small the negative number can get)

The following numbers, however, are not acceptable, namely: stand-alone minus / plus sign, negative zero, numbers with one or more leading zeros, numbers with a leading plus sign, and incomplete decimals, for example:

-
+
-0
0123456789.1234
007
+0.1
+123456789.1234
.1234
1.

Thanks :)


Solution

  • This will do it: ^(-?0\.\d{1,4}|-?[1-9]\d*(\.\d{1,4})?|0)$. Here you can play around: https://regex101.com/r/e7ch1G/3