I am trying to check the user input, I want the phone number to be like 000-0000
.
But my code here does not work as I want. I input
"123-4444444"
and it also matches.
I am not familiar with Regex, but I need to use it, so can you tell me how to change the pattern?
Regex regex = new Regex(@"\d{3}-\d{4}");
if (!(regex.IsMatch(txtUpdatePhoneNumber.Text)))
{
MessageBox.Show("Phone number format should be 000-0000", "Error");
}
CodePudding user response:
You have to specify start and beginning
Please check the regex here: https://regex101.com/r/MZ4YPo/1
^
: start of string
$
: end of string
^\d{3}-\d{4}$
Regex regex = new Regex(@"^\d{3}-\d{4}$");
if (!(regex.IsMatch(txtUpdatePhoneNumber.Text)))
{
MessageBox.Show("Phone number format should be 000-0000", "Error");
}
CodePudding user response:
it looks for me as you were writing a validator for user input. so (unfortunately I have to guess) in this respect you want only this number and nothing before or after.
Regex regex = new Regex(@"^\d{3}-\d{4}$");
This would mean you need to ensure that the first 3 digits are really in the beginning of the string using ^
otherwise IsMatch
would return true
because it finds the pattern in "something000-0000"
and that after the last 4 digits the string is at its end using $
otherwise IsMatch
would return true
because it finds the pattern in "000-0000something"