Remove non-numeric characters from a string

3

Example:

I have the following string

  

"M1245D454"

I need only leave the numbers on it.

M and D, are examples, I want to remove any non-numeric character.

Is there any function in C # or VB.NET for this?

    
asked by anonymous 14.04.2016 / 21:35

3 answers

12

If there is something ready I do not know to tell you.

But it's simple, you can do with a very basic Regex

string ApenasNumeros(string str)
{
    var apenasDigitos = new Regex(@"[^\d]");   
    return apenasDigitos.Replace(str, "");
}

You also have the regex-free option

str = new string(str.Where(char.IsDigit).ToArray());
    
14.04.2016 / 21:39
2
public static void Main()
{
string str = "M1245D454"; 
Console.WriteLine("Entrou como: '{0}'", str);
str = str.Replace("M", "").Replace("D", "");
Console.WriteLine("Saiu como: '{0}'", str);
}
//Resultado 
// Entrou como: 'M1245D454'
//Saiu como: '1245454'

The link of the string.Replace method

obs: reply to the original question

But for the removal of any non-numeric character I recommend using regex as the answer made by the other colleague. Here's the link for class regex and its constructors

    
14.04.2016 / 21:50
2

Dim strFiltrado = String.Concat(
    stringOriginal.Where(
        Function(c) "0123456789".Contains(c) ) )
    
25.05.2016 / 13:45