2

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})$");
Mr world wide
  • 3,879
  • 6
  • 34
  • 77

1 Answers1

1

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.

Wiktor Stribiżew
  • 484,719
  • 26
  • 302
  • 397