Showing posts with label Regex. Show all posts
Showing posts with label Regex. Show all posts

Quickly Replace Non-Numeric characters In a String

If you have a requirement where in you do not want to prevent users from entering non-numeric characters in a textbox, however want to filter out all the non-numeric characters, then here's how to do so:

First import the namespace System.Text.RegularExpressions;

C#


    // Replace non-numeric characters 

    string str = "12d223*23#22";

    string newStr = Regex.Replace(str, @"[^\d]", "");

 

    // Displays 122232322



VB.NET


    ' Replace non-numeric characters 

    Dim str As String = "12d223*23#22"

    Dim newStr As String = Regex.Replace(Str, "[^\d]", "")

 

    ' Displays 122232322