user196442
user196442

Reputation:

.NET Regex, only numeric, no spaces

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?

Upvotes: 6

Views: 14842

Answers (2)

Enor
Enor

Reputation: 29

this regex works perfecttly

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

Upvotes: 1

JaredPar
JaredPar

Reputation: 755587

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+$

Upvotes: 14

Related Questions