1

I want to catch any number greater than 0, from 0.01 too 999, where .01 is also acceptable.

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

Should match: (if decimal exists, max 3 numbers before and 2 after.)

.01
.1
0.01
0.1
1
10
10.1
10.11
105.1
999.99
88.00

Should fail:

12345678.54
00564.5412
00.451
1.
,25
..25
0025
01
00,25
0
.0
0.001
999.001
e123.12
1000

http://regex101.com/r/qZ5lC6/1 - The .x and limiting the characters before and after the optional decimal is where it's getting troublesome.

ditto
  • 5,917
  • 10
  • 51
  • 88
  • 1
    possible duplicate of [regular expression for floating point numbers](http://stackoverflow.com/questions/12643009/regular-expression-for-floating-point-numbers) – tripleee Nov 13 '14 at 04:06

2 Answers2

8

based on what you posted use this pattern

^(?=.*[1-9])(?!0\d)(\d{0,3}(?:\.\d{1,2})?)$

Demo

^               Start of string/line
(?=             Look-Ahead
  .             Any character except line break
  *             (zero or more)(greedy)
  [1-9]         Character Class [1-9]
)               End of Look-Ahead
(?!             Negative Look-Ahead
  0             "0"
  \d            <digit 0-9>
)               End of Negative Look-Ahead
(               Capturing Group \1
  \d            <digit 0-9>
  {0,3}         (repeated {0,3} times)
  (?:           Non Capturing Group
    \.          literal "."
    \d          <digit 0-9>
    {1,2}           (repeated {1,2} times)
  )             End of Non Capturing Group
  ?             (zero or one)(greedy)
)               End of Capturing Group \1
$               End of string/line
alpha bravo
  • 7,838
  • 1
  • 19
  • 23
3

For the purpose of completeness, here is a solution without look-around assertions:

^([1-9]\d{0,2}(\.\d{1,2})?|0?\.(\d[1-9]|[1-9]\d?))$

(Make the capturing group non-capturing if necessary)

[1-9]\d{0,2}(\.\d{1,2})? matches integers from 1 to 999, or decimal numbers from 1.00 to 999.99, both cases without leading 0 and the fractional part can have 1 or 2 digits.

0?\.(\d[1-9]|[1-9]\d?) matches 0.01 to 0.99, with the 0 in the integer part optional and the fractional part consists of 1 or 2 digits.

nhahtdh
  • 55,989
  • 15
  • 126
  • 162