2

I want to check if a string with an undefined length consist of only numbers. Example:

"234324" = true
"er32" = false
"1" = true

the way I tried to solve this problem is like this:

public bool Validate(string input)
{
    return (Regex.IsMatch(input, @"^\d+$")) ? true : false;
}

now im not a big hero with regular expressions, but according to everything I could find on the internet either the expression "^\+$" or "^[0-9]$" would work, but it doesnt :(

2
  • 3
    Does your input contain a newline of some sort? This, and $ not matching on it would be the only reason why you code does not work to my eyes.
    – fge
    Dec 16, 2011 at 13:05
  • Are you getting false positive or false negatives? Also pet peeve, but condition ? true : false is equivalent to condition
    – Ray
    Dec 16, 2011 at 13:17

5 Answers 5

11

There is no need for a RegExhere, you can use int.TryParse to check if a string is a valid integer.

public bool Validate(string input)
{
     int myNumber;
     return int.TryParse(input, out myNumber);
}

Note that IsMatchalready returns a bool, ? true : false is useless.

2
  • 1
    Only if the number fits in an int.
    – Ray
    Dec 16, 2011 at 13:13
  • This is not regex. but question is regex. and your answer is not true when i have very large string May 11, 2015 at 4:48
3
int number;
return int.TryParse(input, out number);
3

use "^[0-9]+$" insead of "^[0-9]$" (notice the + character) which means that multiple characters will be evaluated.

2

^\d+$ should work and does work for me. Your two examples at the end won't work because ^\+$ is missing the d (I assume this is a typo, but it should be ^\d+$) and the second one needs a plus after the closing square bracket (i.e. ^[0-9]+$).

I would check to see if trimming the input makes a difference, you might have whitespace that is causing problems. Otherwise your error is somewhere else and not in this code.

2

If the string really can be of arbitrary length, then Ray is right in saying that the code in the accepted answer will fail if the number represented by the string is > Int32.MaxValue.

The following example will return false instead of true:

bool isNumber = Validate(Int64.MaxValue.ToString()); // isNumber == false

Here is an alternative solution that works for strings of arbitrary length:

public bool Validate(string input)
{
   return input.ToCharArray().All(c => Char.IsDigit(c));    
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.