5

I've written two Regexp's that allow for the following formats:

  • X
  • X.
  • X.Y

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.

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

4 Comments

@fractal5 \d will allow 0001 for instance, so you may want to use: ^([1-9][0-9]*)?[0-9].?\d{0,2} (or something similar)
@fractal5 - Perhaps you intended this as a comment on the question? Because as a comment on my answer - since my answer is based on the requirements spelled out in the question, which don't state that leading 0's should be excluded - it's incorrect.
Got it. Yeah I just realized that the ? after the ) is what makes it optional. Thanks for the simple solution.
@Mark Adelsberger It's just a comment for the OP taking into account your improvement of his regex. It looks more relevant to me to keep them together. Your answer is perfect accordingly to the requirements ! Keep cool :-)
5

Is there a better way to write this?

You can use this regex without any groups:

^\d+\.?\d{0,2}$

RegEx Demo

\d{0,2} allows for absence of any digits after period. Also note that \.{0,1} is same as \.?

1 Comment

@fractal5 \d will allow 0001 for instance, so you may want to use: ^([1-9][0-9]*)?[0-9].?\d{0,2} (or something similar)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.