Reputation: 4814
i am looking for a regex to accept only this number not any other format.
123-456-7890
I have tried this but accepting diff formats as well.
Regex regexPhoneNumber = new Regex(@"^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$");
Upvotes: 2
Views: 3170
Reputation: 627101
You may use
Regex regexPhoneNumber = new Regex(@"\A[0-9]{3}-[0-9]{3}-[0-9]{4}\z");
It will accept a string that starts with 3 digits, then has -
, then 3 digits, -
, and then 4 digits followed with the very end of string position.
Details:
\A
- start of string[0-9]{3}
- 3 ASCII digits-
- a hyphen[0-9]{3}
- 3 digits-
- again a hyphen[0-9]{4}
- 4 digits\z
- the very end of the string (no final newline can follow, as is the case with $
anchor).Note that in case you want to use \d
instead of [0-9]
to shorten the pattern, and still match ASCII only digits, pass RegexOptions.ECMAScript
option to the Regex object.
Upvotes: 1