76

I need a regular expression pattern to only accept positive whole numbers. It can also accept a single zero.

I do not want to accept decimals, negative numbers, or numbers with leading zeros.

Any suggestions?

1
  • 2
    Go to regexr.com and try it out! Commented Dec 6, 2018 at 14:28

5 Answers 5

123
^(0|[1-9][0-9]*)$
Sign up to request clarification or add additional context in comments.

5 Comments

Should it include an optional comma, in case the format allows it (like 1,000,000)?
No, It should not accept commas.
This would do the job: ^(0|[1-9][0-9]*|[1-9][0-9]{0,2}(,[0-9]{3,3})*)$
Can you please explain this Regex?Why @"^\\d$" won't work?
"^\d$" only does single digits, but "^\d{1,}$" does one or more (Powershell V4 syntax)
21

"[1-9][0-9]*|0"

I'd just use "[0-9]+" to represent positive whole numbers.

2 Comments

if i use grepl("[0-9]+","1111a") in R, it gives me TRUE
@AmanMathur ^[0-9]+$ then.
19

This will allow decimal numbers (or whole numbers) that don't start with zero:

^(([1-9]*)|(([1-9]*)\.([0-9]*)))$

If you want to allow numbers that start with zero, you can do :

^(([0-9]*)|(([0-9]*)\.([0-9]*)))$

1 Comment

These will allow the empty string and '.' by itself.
5
/([1-9][0-9]*)|0/

Comments

4
/^0|[1-9]\d*$/

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.