简体   繁体   English

VB.NET条件与正则表达式匹配

[英]VB.NET conditionals with a regex match

I constructed a code that checks if the content in a textbox is a string or an integer. 我构造了一个代码,用于检查文本框中的内容是字符串还是整数。 What i do is the following : 我的工作如下:

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

Now all is working just fine, untill i type in 11 or more numbers in the textbox, after which the code suddenly tells me that (eg) 012345678912 is a string (!) 现在一切正常,直到我在文本框中输入11个或更多数字 ,然后代码突然告诉我,例如012345678912是字符串(!)。

So to be clear, when i type the following numbers : 所以要清楚,当我键入以下数字时:

  • 12345 -> msgbox tells me the entry is "Not a correct TVA number" 12345-> msgbox告诉我输入的内容是“ TVA号码不正确”
  • 123456789 -> msgbox tells me the entry is "Not a correct TVA number" 123456789-> msgbox告诉我输入内容为“ TVA号码不正确”
  • 0123456789 -> msgbox says it's OK 0123456789-> msgbox说还可以
  • 01234567891 -> msgbox tells me the entry is "Not a correct TVA number" 01234567891-> msgbox告诉我输入内容为“ TVA号码不正确”
  • 012345678912 -> msgbox tells me the entry is suddenly a string ! 012345678912-> msgbox告诉我条目突然是一个字符串!
  • some text -> msgbox says it's a string so it's OK 一些文本-> msgbox说它是一个字符串,所以没关系

Maybe i'm missing something obvious here, but i looked at the code over and over again and i tested the regular expressions a few times in other applications, where they work just fine. 也许我在这里遗漏了一些明显的东西,但是我一遍又一遍地看了一下代码,并在其他应用程序中对正则表达式进行了几次测试,在这些应用程序中它们正常工作。

What is it that i'm overlooking here please ? 请问我在这里俯瞰什么?

Regards Wim 关于Wim

That value is too large for an Integer , so it overflows and Int32.TryParse returns false . 对于Integer ,该值太大,因此它将溢出并且Int32.TryParse返回false

You could use this: 您可以使用此:

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

or use Int64.TryParse instead which allows larger numbers. 或改用Int64.TryParse允许更大的数字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM