Reputation: 2132
I've written two Regexp's that allow for the following formats:
Where Y can be 1 or 2 digits. And X is unlimited.
Regex1: ^\d+(?:\.{0,1})(?:\d{1,2})?$
Regex2: ^\d+\.{0,1}(?:\d{1,2})?$
Is one better than the other?
Is there a better way to write this?
Also, why doesn't this one work where the dot is just set as optional: ^\d+(?:\.)(?:\d{1,2})?$
Thanks.
Upvotes: 5
Views: 9166
Reputation: 45659
The reason ^\d+(?:\.)(?:\d{1,2})?$
doesn't work is that it does not make the . optional as you say. the (?:
... )
is not how you make something optional; its main use is grouping multiple things together (so that a subsequent ?
, '+', etc. could modify the group) without producing a capture value.
Make something optional by following it with a ?
. So:
^\d+\.?(?:\d{1,2})?$
should work. It's simpler - so imo preferable - to either of the other options you showed. Simpler still:
^\d+\.?\d{0,2}$
ought to be fine.
Upvotes: 7
Reputation: 785038
Is there a better way to write this?
You can use this regex without any groups:
^\d+\.?\d{0,2}$
\d{0,2}
allows for absence of any digits after period. Also note that \.{0,1}
is same as \.?
Upvotes: 5