具有正则表达式匹配的VB.NET条件

时间:2016-07-27 11:23:05

标签: regex vb.net

我构造了一个代码,用于检查文本框中的内容是字符串还是整数。 我所做的是以下内容:

Imports System.Text.RegularExpressions

Public Class Form1

Private Sub btnCheck_Click(sender As Object, e As EventArgs) Handles btnCheck.Click

    Dim value As String = txtBox.Text

    Dim i As Integer
    If (Integer.TryParse(value, i)) = True Then
        If IsValid(value) = True Then
            MsgBox(value & " is a correct entry")
        Else
            MsgBox("Not a correct TVA number !")
        End If
    Else
        MsgBox(value & " is a string")
    End If
End Sub

Function IsValid(ByRef value As String) As Boolean
    Return Regex.IsMatch(value, "^0[1-9]{9}$")
End Function

End Class

现在一切正常,直到我在文本框中键入 11或更多数字,之后代码突然告诉我(例如)012345678912是一个字符串(!)

所以要明确的是,当我输入以下数字时:

  • 12345 - > msgbox告诉我条目是"不是正确的TVA号码"
  • 123456789 - > msgbox告诉我条目是"不是正确的TVA号码"
  • 0123456789 - > msgbox说没关系
  • 01234567891 - > msgbox告诉我条目是"不是正确的TVA号码"
  • 012345678912 - > msgbox告诉我这条目突然变成了一个字符串!
  • 一些文字 - > msgbox说这是一个字符串,所以没关系

也许我在这里遗漏了一些明显的东西,但我一遍又一遍地看着代码,我在其他应用程序中测试了几次正则表达式,在那里它们工作得很好。

我在这里俯瞰的是什么?

此致 维姆

1 个答案:

答案 0 :(得分:2)

该值对于Integer而言太大,因此它会溢出而Int32.TryParse会返回false

你可以用这个:

If value.All(AddressOf Char.IsDigit) Then
    If IsValid(value) = True Then
        MsgBox(value & " is a correct entry")
    Else
        MsgBox("Not a correct TVA number !")
    End If
Else
    MsgBox(value & " is a string")
End If

或使用Int64.TryParse而不是允许更大的数字。

相关问题