user2653652
user2653652

Reputation: 57

vb.net string contains only 4 digit numbers(or a year)

how can i check if a string only contains 4 digit numbers ( or a year )
i tried this

 Dim rgx As New Regex("^/d{4}")      
    Dim number As String = "0000"
    Console.WriteLine(rgx.IsMatch(number)) // true
    number = "000a"
    Console.WriteLine(rgx.IsMatch(number)) // false
    number = "000"
    Console.WriteLine(rgx.IsMatch(number)) //false
    number = "00000"
    Console.WriteLine(rgx.IsMatch(number))  // true <<< :(

this returns false when its less than 4 or at characters but not at more than 4

thanks!

Upvotes: 3

Views: 2738

Answers (3)

AStopher
AStopher

Reputation: 4550

You should use the .NET string manipulation functions.

Firstly the requirements, the string must:

  • Contain exactly four characters, no more, no less;
  • Must consist of a numeric value

However your aim is to validate a Date:

Function isKnownGoodDate(ByVal input As String) As Boolean 'Define the function and its return value.
    Try 'Try..Catch statement (error handling). Means an input with a space (for example ` ` won't cause a crash)
        If (IsNumeric(input)) Then 'Checks if the input is a number
            If (input.Length = 4) Then
                Dim MyDate As String = "#01/01/" + input + "#"
                If (IsDate(MyDate)) Then
                    Return True
                End If
            End If
        End If
    Catch
        Return False
    End Try
End Function

You may experience a warning:

Function isKnownGoodDate does not return a value on all code paths. Are you missing a Return statement?

this can be safely ignored.

Upvotes: -1

Use LINQ to check if All characters IsDigit:

Dim result As Boolean = ((Not number Is Nothing) AndAlso ((number.Length = 4) AndAlso number.All(Function(c) Char.IsDigit(c))))

Upvotes: 0

Joel Coehoorn
Joel Coehoorn

Reputation: 416059

I actually wouldn't use a regex for this. The expression is deceptively simple (^\d{4}$), until you realize that you also need to evaluate that numeric value to determine a valid year range... unless you want years like 0013 or 9015. You're most likely going to want the value as an integer in the end, anyway. Given that, the best validation is probably just to actually try to convert it to an integer right off the bat:

Dim numbers() As String = {"0000", "000a", "000", "00000"}
For Each number As String In numbers
    Dim n As Integer
    If Integer.TryParse(number, n) AndAlso number.Length = 4 Then
        'It's a number. Now look at other criteria

    End If 
Next 

Upvotes: 5

Related Questions