views:

1113

answers:

4

I need a regular expression for a text field in my asp.net website

which should lie in between

0000 to 9999

it is not be

0 to 9999

+24  A: 

I think this could be:

^\d{4}$

Don't forget to escape it if you are using c#

string numReg = @"^\d{4}$";
Jhonny D. Cano -Leftware-
The "^" ensures that the digits appear at the beginning of the text field, i.e. that there is nothing else before them. The "$" ensures that the digits appear at the end of the text field, i.e. that there is nothing else after them. "\d" is equivalent to [0-9], and "{4}" specifies the exact number of occurences of the "\d".
Adam Bernier
+8  A: 

Along with the other answers, you could also try this.

^[0-9]{4}$
Scott Ivey
Using `0-9` is better since `\d` can contain more characters than one expects. The regex needs to be anchored though.
Sinan Ünür
+7  A: 

Use a gigantic switch statement!

switch(val){
    case "0000":
      print "0000";
      break;
    // ...
    case "9999":
      print "I'm sick of typing";
      break;
 }
samoz
+1 lol ;-) (since there is already a good answer with +15)
David Zaslavsky
Very humorous. Though, I'm afraid of what will happen when you validate `9999` and get back `I'm sick of typing`. :-P
Marcus Griep
I community wiki'd this because I expected at least -3, oh well.
samoz
A: 

Using a little logic. (Humorous, similar to "gigantic switch")

Ruby

def validate num
  return false unless num.length == 4
  return false unless num.to_i.between?(-1, 10000)
  num.each_char {|ch| return false unless '0123456789'.include? ch }
  true
end

puts validate '404' #false
puts validate '9321' # true
puts validate '-302' #false
puts validate 'AAAA' # false
nilamo
Would 'AAAA' cause this to return true? I'm actually asking; I don't know Ruby.
samoz
Not anymore ;)
nilamo
'some_string'.to_i returns 0 for stings that are not ints, so it would have before, but has been amended so it won't now.
nilamo