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

Asked

Viewed 1,093 times

7

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

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

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

For that, 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("/","")

This way I can take only the numbers and put in the input with the mask. Now I came across letters, how do I replace letters with nothing? Something like: Replace("letras","")

2 answers

8


You can just take the numbers and don’t have to do the rest Replace:

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

Or:

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

Example here

  • Thank you, so much show... it worked perfect!

  • I recommend that you only save numbers in the database OR mount your form to process this data, one possibility is to use a mask in the input so that it automatically does the phone Pattern: (xx) 99999-9999

  • If you want/like jquery, I recommend this resource: https://igorescobar.github.io/jQuery-Mask-Plugin/

  • For what I saw must be Totvs , in the Configurator you set the mask in the field.

  • Yes, @Daviddias , I’m dealing on the front the data entry, putting a mask of the library Jquery (99)9999-9999? 9. The problem itself was not the saving, for the saving will only number because of the mask. Loading the data (Edit), which from the database could come with characters other than number.

  • @Motta, we don’t use Totvs .

  • @Daniellearrudatorres , beauty is that Totvs uses fields with these name A!_Z....

Show 2 more comments

8

I would do this because it’s 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();
    }
}

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

Browser other questions tagged

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