user1447679
user1447679

Reputation: 3230

I need this regex expression to allow 0, 0.00, or 00.00

I know there are a ton of questions in regards to regex, but I've never really been able to wrap my head around how these work.

Here's my regex:

(?!^0*$)(?!^0*\.0*$)^\d{0,10}(\.\d{1,2})?$

It's for numeric values only, with up to two decimal places.

I'm looking for an answer, but more specifically, what does what so I can better understand it. I need to be able to match 0, 0.00. or 00.00 in this expression.

Thank you.

Upvotes: 2

Views: 5718

Answers (3)

NishantMittal
NishantMittal

Reputation: 537

Try this

\d{1,3}(.)\d{1,2}

or

\d{1,3}.\d{2}

Upvotes: 0

johntellsall
johntellsall

Reputation: 15170

Here's a pattern and check in Python

source

import re

nums = ['0', '0.00', '00.00']

# match one or two zeros
# After, there's an optional block: a period, with 1-2 zeros
pat = re.compile('0{1,2}(\.0{1,2})?')

print all( (pat.match(num) for num in nums) )

output

True

Upvotes: 0

user578895
user578895

Reputation:

Remove the first two sets of parenthesis, just make it:

^\d{0,10}(\.\d{1,2})?$

This says:

^           -- start of line
\d{0,10}    -- 0 - 10 digits
(
  \.\d{1,2} -- a dot followed by 1 or 2 digits
)?          -- make the dot and 2 digits optional
$           -- end of line

As for the two that were removed:

(?!^0*$)     -- do not allow all zeros (0000000)
(?!^0*\.0*$) -- do not allow all zeros with a dot in the middle (0000.0000)

(?!          -- "negative lookahead", e.g. "Do not allow"
  ^          -- start of line
  0*         -- any number of zeros
  $          -- end of line
)

Upvotes: 2

Related Questions