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
  • 3,076
  • 7
  • 32
  • 69
  • You're just trying to match zeros? Or any numerical value? –  Jun 30 '14 at 22:32
  • The regex I posted allows any numeric entry up to like, 10 places on the left, and 2 on the right.. So 1.00, 10.00, 100000.00, 100000.25, etc. I need it to also be able to have 0, 0.00, 00.00 – user1447679 Jun 30 '14 at 22:33
  • [Reference - What does this regex mean?](http://stackoverflow.com/q/22937618/1048572) – Bergi Jun 30 '14 at 22:34

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
)
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
  • 14,394
  • 4
  • 46
  • 40
0

Try this

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

or

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

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