Monday, January 24, 2011

How to identify if string contain a number?

System.Text.RegularExpressions.Regex.IsMatch(input, "\d")

So times you will need to check a string, to see if it contains a number.
What’s the best way to do this?


There are several solutions like this function :

TryParse approach:



Public Shared Function IsNumeric(Expression As Object) As Boolean
    Dim isNum As Boolean
    Dim retNum As Double
    isNum = [Double].TryParse(Convert.ToString(Expression), System.Globalization.NumberStyles.Any, System.Globalization.NumberFormatInfo.InvariantInfo, retNum)
    Return isNum
End Function

Check Characters in String approach:



Public NotInheritable Class Extensions
    Private Sub New()
    End Sub
    <System.Runtime.CompilerServices.Extension> _
    Public Shared Function IsNumeric(s As String) As Boolean
        For Each c As Char In s
            If Not Char.IsDigit(c) AndAlso c <> "."C Then
                Return False
            End If
        Next
 
        Return True
    End Function
End Class

What about locales where '.' is the group separator, not the comma (e.g. pt-Br)? What about negative numbers?
Group separators (commas in English)? Currency symbols?
TryParse() can manage all of these as required using NumberStyles and IFormatProvider.

Regular Expressions approach:



System.Text.RegularExpressions.Regex.IsMatch(input, "^\d+$")

This will return true if input is all numbers


If you just want to know if it has one or more numbers mixed in with characters, leave off the ^ + and$.



System.Text.RegularExpressions.Regex.IsMatch(input, @"\d")

Actually I think it is better than TryParse because a very long string could potentially overflow TryParse.

Summary


In my opinion the winner is the Regular Expressions Method

No comments:

Post a Comment