tags:

views:

143

answers:

1

I'm looking for a regular expression that accepts only numerical values and no spaces. I'm currently using:

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

which works fine, but it accepts values that consist ONLY of spaces. What is wrong with it?

+6  A: 

The reason why is that * will accept 0 or more. A purely empty string has 0 numbers and hence meets the requirements. You need 1 or more so use + instead.

^(0|[1-9][0-9]+)$

EDIT

Here is Andrews more robust and simpler solution.

^\d+$
JaredPar
+1 Too fast! :)
Andrew Hare
Cheers for the quick answer, however it will still pass a string that has only spaces :(
Damage
Your suggested regex `^(0|[1-9][0-9]+)$` does not support numbers greater than zero and less than ten.
Greg Hewgill
But doesn't * only apply to the last set of digits? OP is matching either 0 or 1-9 followed by zero or more 0-9.
Brian Rasmussen
@Damage are you sure you're actually utilizing the Regex framework in .Net correctly? a simple regex such as ^\d+$ should never ever match anything but unsigned integer text strings. Try posting your .Net code
kastermester