1

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.

user1447679
  • 2,777
  • 5
  • 25
  • 57

3 Answers3

2

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
)
Mark Kahn
  • 81,115
  • 25
  • 161
  • 212
0

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
johntellsall
  • 11,853
  • 3
  • 37
  • 32
0

Try this

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

or

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

NishantMittal
  • 551
  • 1
  • 4
  • 17
  • Please, don't post twice an invalid answer: http://stackoverflow.com/a/36492441/372239 – Toto Apr 08 '16 at 08:52