Remove formatting from a string: “(123) 456-7890” => “1234567890”?

后端 未结 14 729
一整个雨季
一整个雨季 2021-02-05 01:12

I have a string when a telephone number is inputted - there is a mask so it always looks like \"(123) 456-7890\" - I\'d like to take the formatting out before saving it to the D

14条回答
  •  深忆病人
    2021-02-05 01:20

    As many answers already mention, you need to strip out the non-digit characters first before trying to parse the number. You can do this using a regular expression.

    Regex.Replace("(123) 456-7890", @"\D", String.Empty) // "1234567890"
    

    However, note that the largest positive value int can hold is 2,147,483,647 so any number with an area code greater than 214 would cause an overflow. You're better off using long in this situation.

    Leading zeros won't be a problem for North American numbers, as area codes cannot start with a zero or a one.

提交回复
热议问题