locked
RegEx Needed Please RRS feed

  • Question

  • User865450124 posted

    I am in search of a RegEx that will strip out all non-numeric characters returning only the numeric characters.

    2301  Returns   2301
    2301-A  Returns   2301
    ABCD   Returns [Zero Length String]
    ~!@#$%^&*()_+|}{":?><`-=[]\';/.,   Returns [Zero Length String]

    And now that I thnk about it, also a second RegEx that strips out everything that is not a letter [A-Z][a-z].

     

    Monday, January 14, 2013 9:15 PM

Answers

  • User281315223 posted

    To Remove Non-Numerical Characters:

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

    or in method form :

    string NumericOnly(string yourString)
    {
        Regex numericOnly = new Regex(@"[^\d]");   
        return numericOnly.Replace(yourString, "");
    }

    To Remove All Non-Alphabetic:

    string alphabeticOnly = Regex.Replace(yourString, @"[^a-zA-Z]", "");

    and as a method : 

    string AlphabeticOnly(string yourString)
    {
        Regex alphaOnly = new Regex(@"[^a-zA-Z]");   
        return alphaOnly.Replace(yourString, "");
    }

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, January 14, 2013 9:18 PM

All replies

  • User281315223 posted

    To Remove Non-Numerical Characters:

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

    or in method form :

    string NumericOnly(string yourString)
    {
        Regex numericOnly = new Regex(@"[^\d]");   
        return numericOnly.Replace(yourString, "");
    }

    To Remove All Non-Alphabetic:

    string alphabeticOnly = Regex.Replace(yourString, @"[^a-zA-Z]", "");

    and as a method : 

    string AlphabeticOnly(string yourString)
    {
        Regex alphaOnly = new Regex(@"[^a-zA-Z]");   
        return alphaOnly.Replace(yourString, "");
    }

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, January 14, 2013 9:18 PM
  • User281315223 posted

    I'm throwing an updated answer as it was brought to my attention that this was posted in the Visual Basic forum so I'll provide the same answers but with Visual Basic syntax : 

    To Remove Non-Numerical Characters:

    Dim numericOnly As String = Regex.Replace(yourString, @"[^\d]", "")

    or in method form :

    Function NumericOnly(ByVal yourString As String) As String
    {
        Dim numericOnly As
    new Regex(@"[^\d]")
       
    return numericOnly.Replace(yourString, "")
    }

    To Remove All Non-Alphabetic:

    Dim alphabeticOnly As String = Regex.Replace(yourString, @"[^a-zA-Z]", "")

    and as a method : 

    Function AlphabeticOnly(ByVal yourString As String) As String
    {
        Dim
    alphaOnly = new Regex(@"[^a-zA-Z]")
       
    return alphaOnly.Replace(yourString, "")
    }
    Thursday, March 7, 2013 5:55 PM