Remove non-numeric characters from a string

Asked

Viewed 10,165 times

5

Example:

I have the following string

"M1245D454"

and I need to just leave the numbers on it.

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

There is some function in C# or VB.NET for this?

3 answers

15


If there’s something ready I can’t tell you.

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

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

You also have the option regex-free

str = new string(str.Where(char.IsDigit).ToArray());

4

It is possible to do without using Regex too, using only Linq (remembering that all String is also a IEnumerable(Of Char). In VB.NET I usually implement so:

Dim strFiltrado = String.Concat(
    stringOriginal.Where(
        Function(c) "0123456789".Contains(c) ) )

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'

Follows the link of the string method. Replace

Obs: Answer to original question

But for the removal of any non-numeric character I recommend using regex as the response made by the other colleague. Follows the link class-related regex and its builders

  • 1

    @Felipewalleg has the history of the changes here, if you need to adjust something, you can edit again. http://answall.com/posts/123453/revisions

Browser other questions tagged

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