vb.net 字符串仅包含 4 位数字(或年份)

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

如何检查字符串是否仅包含 4 位数字(或年份)
我试过了

 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 <<< :(

此 returns 小于 4 或字符但不超过 4 时为 false

谢谢!

您应该使用 .NET 字符串操作函数。

首先要求,字符串必须:

  • 正好四个字符,不多不少;
  • 必须由数值组成

但是您的目标是验证 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

您可能会遇到警告:

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

这可以安全地忽略。

使用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))))

我实际上不会为此使用正则表达式。该表达式看似简单 (^\d{4}$),直到您意识到您还需要评估该数值以确定有效的年份范围......除非您想要像 00139015 这样的年份.无论如何,您最终很可能希望该值是一个整数。鉴于此,最好的验证可能只是实际尝试立即将其转换为整数:

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