8

I need a regex to validate integer numbers. 05 and 00 are not allowed but 0 is allowed. Currently I have this:

/^[1-9]\d*$/

But it does not allow 0. Thanks for help.

2 Answers 2

12
 ^(?:[1-9]\d*|0)$

This is your pattern...

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

7 Comments

No reason to use capture grouping. Better one would be ^(?:[1-9]\d*|0)$
Yes, you're right. I used parentheses to emphasize OR. Simply ^[1-9]\d*|0$ should do the trick.
No, you must not remove the parentheses, or you'll separate the regex into (^[1-9]\d*)|(0$)!
@AdamWolski - Wrong, that would match 12abc or xyz0
@RafaelSedrakyan - (?: ) Non-capturing parentheses group the regex so you can apply regex operators, but do not capture anything and do not create backreferences.
|
7

Your regex should be ^(?!0.)\d+$

Comments

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.