Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex doesn't work as I need

Tags:

c#

regex

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.

like image 420
David Shochet Avatar asked Dec 08 '22 22:12

David Shochet


2 Answers

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.

like image 160
Rob Volgman Avatar answered Dec 27 '22 20:12

Rob Volgman


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

return Regex.IsMatch(id, "^[0-9]{9,10}$");
like image 29
Aghilas Yakoub Avatar answered Dec 27 '22 19:12

Aghilas Yakoub