Replace letter by empty or blank, something like Replace ("letters", "")

6

There is a A1_ZTEL field in the database that is varchar(15) . This way, each user entered a record of all forms, with bar, dot, comma and letter.

Now I need to mount a form and read this field from another table that is varchar(40) and save on A1_ZTEL ( varchar 15 ).

Before I show in FORM, taking only the first 15 digit and in the format (99)9999-9999?9 (phone or cel). So far so good.

For this, I treat the bank's return, and I do it with Replace() and Trim()

Example:

  p.ZC_CELULAR = reader["A1_ZTEL"].ToString().Trim().Substring(0,15).Replace("-","").Replace(".","").Replace(",","").Replace("/","")

In this way I can only get the number and put it in input with the mask. Now I came across letters, how do I replace letters for nothing? Something like: Replace("letras","")

    
asked by anonymous 11.04.2018 / 21:47

2 answers

5

You can get only the numbers and do not need to do the other Replace :

p.ZC_CELULAR  = Regex.Replace(reader["A1_ZTEL"].ToString(), "[^0-9]", "");

Or:

p.ZC_CELULAR = Regex.Match(reader["A1_ZTEL"].ToString(), @"\d+").Value;

a>

    
11.04.2018 / 22:01
6

I would do so because it is much more performative

using static System.Console;
using System.Text;

public class Program {
    public static void Main() {
        WriteLine("123.456.789/ 0001-99X".Strip());
        WriteLine("(19)9-98/754?283 A".Strip());
    }
}

public static class StringExt {
    public static string Strip(this string str) {
        var sb = new StringBuilder(str.Length);
        foreach (var chr in str) if (char.IsDigit(chr)) sb.Append(chr);
        return sb.ToString();
    }
}

See working on .NET Fiddle .

    
11.04.2018 / 22:26