You are here: Home > Technical Articles > C# - Miscellaneous String Functions Using Regular Expressions

C# - Miscellaneous String Functions Using Regular Expressions


using System.Text.RegularExpressions;

Get Alpha Numeric
C#
public static string GetAlphaNumeric(string str)
        {
            Regex regDecimal = new Regex("[^A-Za-z0-9]");

            return regDecimal.Replace(str, string.Empty);
        }

VB.NET
Public Shared Function GetAlphaNumeric(ByVal str As String) As String
    Dim regDecimal As New Regex("[^A-Za-z0-9]")
   
    Return regDecimal.Replace(str, String.Empty)
End Function



Get Numeric
C#
public static string GetNumeric(string str)
        {
            Regex regDecimal = new Regex("[^0-9]");

            return regDecimal.Replace(str, string.Empty);
        }

VB.NET
Public Shared Function GetNumeric(ByVal str As String) As String
    Dim regDecimal As New Regex("[^0-9]")
   
    Return regDecimal.Replace(str, String.Empty)
End Function



Get Decimal
C#
public static string GetDecimal(string str)
        {
            Regex regDecimal = new Regex("[^0-9.]");

            return regDecimal.Replace(str, string.Empty);
        }

VB.NET

Public Shared Function GetDecimal(ByVal str As String) As String
    Dim regDecimal As New Regex("[^0-9.]")
   
    Return regDecimal.Replace(str, String.Empty)
End Function



Get Alphabets Only
C#
public static string GetAlphabetsOnly(string str)
        {
            Regex regDecimal = new Regex("[^A-Za-z]");

            return regDecimal.Replace(str, string.Empty);
        }

VB.NET

Public Shared Function GetAlphabetsOnly(ByVal str As String) As String
    Dim regDecimal As New Regex("[^A-Za-z]")
   
    Return regDecimal.Replace(str, String.Empty)
End Function



Replace White Spaces
C#
public static string ReplaceWhiteSpaces(string str, string strReplaceWith)
        {
            Regex regWhiteSpaces = new Regex(@"\s+");
            return regWhiteSpaces.Replace(str, strReplaceWith);
        }

VB.NET
Public Shared Function ReplaceWhiteSpaces(ByVal str As String, ByVal strReplaceWith As String) As String
    Dim regWhiteSpaces As New Regex("\s+")
    Return regWhiteSpaces.Replace(str, strReplaceWith)
End Function



Published On: 02 Aug 2009