1

I need a regular expression that accept only integers or decimals from 1 to 9999.99. I tried this

^(?:[1-9][0-9]{0,4}(?:.d{1,2})?|9999|9999.99)$

but it is also accepting 10000.

Gurmanjot Singh
  • 10,224
  • 2
  • 19
  • 43
Rakhi
  • 35
  • 1
  • 6

3 Answers3

5

There are a few issues in the pattern:

  • This part [1-9][0-9]{0,4} can match 1-5 digits as the quantifier is 0-4 times so it can match 10000 as well
  • You don't need 9999|9999.99 as those can already be matched by 1-9][0-9]{0,4}
  • This part .d matches any char except a newline followed by a d char. You have to escape both to match a dot literally and a single digit
  • With those changes, you can omit the outer capture group

The updated pattern looks like:

^[1-9]\d{0,3}(?:\.\d{1,2})?$
  • ^ Start of string
  • [1-9]\d{0,3} Match a single digit 1-9 and repeat 0 to 3 times a digit 0-9
  • (?:\.\d{1,2})? Optionally match a . and 1 or 2 digits
  • $ End of string

Regex demo

The fourth bird
  • 154,723
  • 16
  • 55
  • 70
  • 1
    This **is** the right answer. I started regex101'ing before reading the answers and my regex turned out identical to yours. – MonkeyZeus Dec 30 '21 at 13:52
2

Try this regex:

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

Demo

Explanation:

  • ^ - matches start of the string
  • 0* - matches 0+ occurrences of digit 0
  • (?!\.\d+) - zero-length match if the current position is not followed by a . and 1+ digits
  • [1-9] - matches a digit from 1 to 9
  • \d{0,3} - matches at-least 0 or at-most 3 occurences of a digit
  • (?:\.\d{1,2})? - matches the decimal . followed by 1 or 2 digits. A ? at the end to make the fractional part optional
  • $ - matches the end of string
Gurmanjot Singh
  • 10,224
  • 2
  • 19
  • 43
  • Thank you. This regex not supporting 22, 33, 434 etc..supports only when adding 0 before each number. Help is appreciated – Rakhi Dec 30 '21 at 12:35
  • [Sorry, but it does match the values you have mentioned](https://regex101.com/r/oQYglx/1) – Gurmanjot Singh Dec 30 '21 at 12:36
  • I'm not sure why you put the `0*(?!\.\d+)`. And if you remove this, it's almost identical with the other answer, but still a bit earlier it seems. – bobble bubble Dec 30 '21 at 15:08
  • @bobblebubble I had added `0*` to match inputs like `01`,`001`,`00001`. I had added `(?!\.\d+)` so as to exclude inputs like `.99`, `.11` as the OP had asked to include the numbers>=1 – Gurmanjot Singh Dec 30 '21 at 15:16
  • Thanks for your quick reply! Well, not clear about that, however upvoted for it already. – bobble bubble Dec 30 '21 at 15:23
1

Another idea but there is not much difference regarding performance (just for fun).

^(?!0)\d{1,4}(?:\.\d\d?)?$

The looakhead (?!0) prevents starting with zero, so we can further match \d{1,4}.

Does not respect leading zeros. See this demo at regex101.

bobble bubble
  • 16,888
  • 3
  • 27
  • 46