Picking up part of the phone

8

At registration, the user registers his phone and this field is masked (99) 99999-9999 and this is saved in the BD. if I want to use only the DDD of this, and the numbers separated, how should I proceed? in case I wanted DDD 99 Number 999999999. I am using MVC, I needed this data so to use it on the Controller.

    
asked by anonymous 03.11.2016 / 03:19

3 answers

9

First replace the special characters and then get the first 2 characters.

// Remove qualquer caracter que não seja numérico
numero = Regex.Replace(numero, "[^0-9]+$", "");
// Pega os 2 primeiros caracteres
ddd = numero.Substring(0, 2);
    
03.11.2016 / 03:40
6

Using regular expressions, we can do this:

using System.Text.RegularExpressions;

var teste = Regex.Match("(12) 3456-7890", @"\((\d{2})\)\s?(\d{4,5}\-?\d{4})");
// teste.Groups[0] imprime o número.
// teste.Groups[1] imprime apenas o DDD.
// teste.Groups[2] imprime apenas o número.

I made a Fiddle .

    
03.11.2016 / 03:45
6

For me the easiest is to make a simple SubString() :

using static System.Console;

public class Program {
    public static void Main() {
        var fone = "(12)34567-8901";
        WriteLine(fone.Substring(1, 2));
        WriteLine(fone.Substring(4, 5) + fone.Substring(10, 4));
    }
}

See running on dotNetFiddle and on CodingGround .

    
03.11.2016 / 04:40