tags:

views:

233

answers:

4

I want a regular expression for only accepting 0-9999

No spaces, no letters. However, "blank"(empty) is allowed.

+8  A: 
\d?\d?\d?\d?

Should do it.

Or more succinctly:

\d{0, 4}

This works because you're saying "0, 1, 2, or 3 digits", where each digit is 0-9. This allows numbers between 0 and 9999, and nothing else.

Note that it allows leading zeros, i.e. 0004 is a valid number.

Eli Bendersky
Seems to allow a space
Coolcoder
@Coolcoder: do you restrict it to be the whole string (i.e. with start string and end string symbols)?
Eli Bendersky
No spaces, period. Not at start, not at end , not in the middle. Just a space on its own is also not allowed. However, "blank" (no value) is ok :)
Coolcoder
@Coolcoder, in case my previous comment wasn't clear: `^\d{0,4}$`: restricting the string to be **only** the digits, not just containing them
Eli Bendersky
+7  A: 

This should work:

[0-9]{0,4}
Can Berk Güder
+7  A: 

well, /\d{0,4}/ is the simplest way, but generally I convert to a number and then do bounds checking

Gareth
+4  A: 

Assuming you don't want to accept numbers left-padded with zeros.

(0|([1-9]\d{0,3}))?

Read as zero or one of the following: 0 or a 1-9 followed by a 0 to 3 digit string.

tvanfosson
Seems to allow a space
Coolcoder
Shouldn't match a space at all since there is no whitespace anywhere in the expression. Depending on how you are using it you may need to add matching characters for the start and end of string: `^(0|([1-9]\d{0,3}))?$`
tvanfosson