Limit digits of whole/integral part of a decimal number using regex

Advertisements

I have a regex (^[1-9]\d*\.?\d{0,2}) to filter a decimal number input.

This is how I think it works:

part1: [1-9]     - start with a non-zero number
part2: \d*       - match 0 or more digits
part3: \.?       - maybe match a dot
part4: \d{0,2}   - match 0 to 2 digits

For a input of 1234567890.56566456465aa, I get a valid match of 1234567890.56

I want to restrict number of digits for \d* from part2. So, I tried to replace it with \d{0,3}. For same input, I get a match of 123456. This is how I think it gave me this result:

1   - from [1-9]
234 - from \d{0,3}
56  - from \d{0,2}

The number part before . (dot) should be 0 to 3 character long. Or, match should skip using part4 if part3 doesn’t exist. For e.g.

1234567890.56566456465aa -> 1234 
1234.567890              -> 1234.56

How can I do this? Here’s related regexr link.

>Solution :

Try this regex:

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

Click for Demo


Explanation:

  • ^ – matches the start of the string
  • [1-9] – matches a single digit in the range 1 to 9
  • \d{0,3} – matches at-least 0 or at-most 3 occurrences of any digit
  • (?:\.\d{0,2})? – matches the optional decimal and fractional part of the number. The fractional part matched will have atleast 1 digit or at most 2 digits

Edit:
To extract 8. for inputs 8.a, you can change the regex to – ^[1-9]\d{0,3}(?:\.\d{0,2})?

Leave a ReplyCancel reply