Picking up part of the phone

Asked

Viewed 1,653 times

10

In the 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 separate numbers, how should I proceed? in case I wanted DDD 99 Number 999999. I’m using MVC, I needed this data so to use in Controller.

  • What is saved in the database is the phone with the mask? Then the field is string?

  • That’s right @Ciganomorrisonmendez

3 answers

12


First replace the special characters and then take 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);
  • Regex.Replace does the removal of the special character ?

  • Exactly! Actually for your case if the regex is only "[ 0-9]+$" solves the problem. I will change

  • ddd = number. Substring(0, 2)); Is closing 2 parentheses at the end, ta missing some, or has been added to more?

  • I was wrong anyway, I removed it now

  • 1

    I did it for your procedure and it worked! TKS

8

Using regular expressions, we can do so:

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.

  • if I want to leave only the number without the dash I do it? 'var test = Regex.Match("(12) 3456-7890", @"(( d{2})) s? ( d{8,9})")'

  • Okay, but in this case it only works if there’s never a trace on the mask.

  • and how this is ignored - ?

  • You can make an if with regex test and apply to whatever is convenient to the case.

  • ?, in regular expression, that is to say: "zero or one occurrences". This regular expression I made therefore makes the use of the stroke optional.

  • @Sorack The advantage of this case is that you don’t exactly need an if. Each group represents specific information.

  • So, but precisely, the if would be to separate the version that could come without the trace in the mask and the with the dash

  • @Sorack what would be the Logic of comparison in If?

  • I’d have to take a regex test...

  • But for what the Gypsy doesn’t need

  • @Gypomorrisonmendez Thanks for the tips it always gives, but the Sorack procedure worked better for my problem by removing the dash. Thanks

Show 6 more comments

6

Browser other questions tagged

You are not signed in. Login or sign up in order to post.