Reputation: 3230
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
Reputation: 15170
Here's a pattern and check in Python
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) )
True
Upvotes: 0
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