Home > Software engineering >  Regular expression for accepting integers, decimal values and limiting by maximum value
Regular expression for accepting integers, decimal values and limiting by maximum value

Time:12-31

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.

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

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.

  • Related