4

I need to validate an account number. It is supposed to have only digits and have 9 or 10 characters. I tried this:

return Regex.IsMatch(id, "[0-9]{9,10}");

But this is not working correctly, as it returns true in case the number is "1234567890blah". Could you please help, as I am not that good with regex?

Thanks.

3 Answers 3

8

You need to indicate that the digits must be the entire string. Put ^ at the start to indicate that it must be the start of the string and $ to indicate that it must be the end.

return Regex.IsMatch(id, "^[0-9]{9,10}$");

See Regular Expression Anchors for more details.

1
  • 1
    Thank you and others who gave the right answer. It does work. Jul 30, 2012 at 15:20
4

Modify by using ( Add start and end caracter, ^ and $ caracter)

return Regex.IsMatch(id, "^[0-9]{9,10}$");
2

This is the problem with regex. There are simpler and clearer solutions.

string acct = "1234567890";
long temp; 

return (acct.Length == 9 || acct.Length == 10)
    && long.TryParse(acct, out temp);
1
  • 2
    It's not a "problem with regex", it's regex being used incorrectly. Regex is intentionally a very precise tool. Jul 30, 2012 at 15:24

Your Answer

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

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