ExtensionMethod.NET Home of 874 C#, Visual Basic, F# and Javascript extension methods

RemoveNonNumericCharacters

Removes any non numeric characters from a string. Overloads for allowing periods and commas to stay.

Source

''' <summary>
''' Removes non-numeric characters from a string.
''' </summary>
''' <param name="value"></param>
''' <returns></returns>
''' <remarks></remarks>
<Extension()> _
Public Function RemoveNonNumericCharacters(ByVal value As String) As String
    Return System.Text.RegularExpressions.Regex.Replace(value, "[^0-9]", "")
End Function

''' <summary>
''' Removes non-numeric characters from a string.  An option is available to allow for a period in case this is used with 
''' a money value or number that requires a decimal place.
''' </summary>
''' <param name="value"></param>
''' <param name="allowPeriod">If true, any periods will be left, if false, all periods will also be removed.</param>
''' <returns></returns>
''' <remarks></remarks>
<Extension()> _
Public Function RemoveNonNumericCharacters(ByVal value As String, ByVal allowPeriod As Boolean)
    If allowPeriod = False Then
        Return RemoveNonNumericCharacters(value)
    Else
        Return System.Text.RegularExpressions.Regex.Replace(value, "[^0-9|^.]", "")
    End If
End Function

''' <summary>
''' Removes non-numeric characters from a string.  An option is available to allow for a period and/or comma in case this is used with 
''' a money value or number that requires a decimal place or a value that requires keeping it's formatting with commas and peroids only.
''' </summary>
''' <param name="value"></param>
''' <param name="allowPeriod">If true, any periods will be left, if false, all periods will also be removed.</param>
''' <param name="allowComma">If true, any commas will be left, if false, all commas will also be removed.</param>
''' <returns></returns>
''' <remarks></remarks>
<Extension()> _
Public Function RemoveNonNumericCharacters(ByVal value As String, ByVal allowPeriod As Boolean, ByVal allowComma As Boolean)
    If allowComma = True And allowPeriod = True Then
        Return System.Text.RegularExpressions.Regex.Replace(value, "[^0-9|^.|^,]", "")
    ElseIf allowPeriod = True And allowComma = False Then
        Return RemoveNonNumericCharacters(value, True)
    ElseIf allowComma = True And allowPeriod = False Then
        Return System.Text.RegularExpressions.Regex.Replace(value, "[^0-9|^,]", "")
    Else
        Return RemoveNonNumericCharacters(value)
    End If
End Function

Example

Dim buf As String = "123 Testing"
buf = buf.RemoveNonNumericCharacters()

Author: John

Submitted on: 1 apr 2010

Language: VB

Type: System.String

Views: 4712