user1884032
user1884032

Reputation: 347

regex to match value up to 2 decimal

I want to have 1 to 5 digits only before the "." and 0 to 2 digits after the "." this is what I have so far for regex.

^\d{1,5}\.?\d{0,2}$

1.00 -- match
11.01 -- match
111.10 -- match
1111.52 -- match
11111.23 -- match
.12 -- no match ... want to match
123456 -- match ... don't want to match because can take up to 5 integers before decimal
1234567 -- match ... don't want to match because can take up to 5 integers before decimal

can anyone help?

Upvotes: 5

Views: 30324

Answers (7)

Shivam Bharadwaj
Shivam Bharadwaj

Reputation: 2296

The easiest way I achieved in python3 is this -

import re

p = re.compile(r'^\d{2}.\d{2}')
print(p.findall('12.59, 11.789, 10.6 lords a-leaping'))

output - ['12.59']

Upvotes: 0

Chazy Chaz
Chazy Chaz

Reputation: 1851

Better late than never:

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

Two groups:

  • One matching from 0 up to 5 digits,
  • The other from 1 up to 2 decimals, allowing 0.12 as .12.

Simple and perfect :)

Upvotes: 0

Alex Shesterov
Alex Shesterov

Reputation: 27525

 /^(\d{0,5}\.\d{1,2}|\d{1,5})$/

Upvotes: 1

Marcellus
Marcellus

Reputation: 1287

I think you need an alternative between numbers with decimal point and numbers without:

^\d{1,5}|\d{0,5}\.\d{1,2}$

Edit:

Thanks to user1884032 for pointing out the missing parentheses:

^(\d{1,5}|\d{0,5}\.\d{1,2})$

Upvotes: 8

A human being
A human being

Reputation: 1220

Try this:

/^\d{0,5}\.\d{0,2}$/

Upvotes: -1

3nafish
3nafish

Reputation: 256

There are two separate issues:

  1. If you want to match 0 to 5 digits before the "." so you'll need the first part to say d{0,5} instead of d{1,5}.

  2. Instead of having an optional "." followed by two more characters, you should have the "." if there are characters after it, but no dot if there are no characters after it. With the following, you will only end up with seven digits if the last two come after the "."

    ^\(d{0,5}\.\d{0,2})|(d{0,5}\.?)$

which means

EITHER
  0-5 digits, then a decimal point, then 0-2 more digits
OR
  0-5 digits, followed by an optional decimal point

This format will also detect legitimate numbers within that range that you didn't list in your test, such as 12345. and 0.12

Upvotes: -1

RichieHindle
RichieHindle

Reputation: 281415

You need this:

^\d{1,5}\.\d{0,2}$

I've removed the ?, which was making the dot optional.

Saying you want to match .12 contradicts your spec - that doesn't have 1-5 digits before the dot. Did you mean {0-5}?

Upvotes: 0

Related Questions