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

后端 未结 14 737
一整个雨季
一整个雨季 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条回答
  •  梦毁少年i
    2021-02-05 01:14

    You can use a regular expression to remove all non-digit characters:

    string phoneNumber = "(123) 456-7890";
    phoneNumber = Regex.Replace(phoneNumber, @"[^\d]", "");
    

    Then further on - depending on your requirements - you can either store the number as a string or as an integer. To convert the number to an integer type you will have the following options:

    // throws if phoneNumber is null or cannot be parsed
    long number = Int64.Parse(phoneNumber, NumberStyles.Integer, CultureInfo.InvariantCulture);
    
    // same as Int64.Parse, but returns 0 if phoneNumber is null
    number = Convert.ToInt64(phoneNumber);
    
    // does not throw, but returns true on success
    if (Int64.TryParse(phoneNumber, NumberStyles.Integer, 
           CultureInfo.InvariantCulture, out number))
    {
        // parse was successful
    }
    

提交回复
热议问题