代码之家  ›  专栏  ›  技术社区  ›  Scott

仅检查vb.net字符串中的数字

  •  5
  • Scott  · 技术社区  · 16 年前

    我想在将字符串附加到StringBuilder之前对其运行检查,以确保字符串中只包含数字字符。一个简单的方法是什么?

    9 回复  |  直到 11 年前
        1
  •  8
  •   Gage    16 年前

    使用integer.typarse()如果字符串中只有数字,它将返回true。Int32最大值是2147483647,所以如果您的值小于此值,那么您的罚款。 http://msdn.microsoft.com/en-us/library/f02979c7.aspx

    您也可以使用double.typarse(),它的最大值为1.7976931348623157E+308,但它允许小数点。

    如果要获取不是整数的值,则可以一次遍历一个字符串。

    string test = "1112003212g1232";
            int result;
            bool append=true;
            for (int i = 0; i < test.Length-1; i++)
            {
                if(!Int32.TryParse(test.Substring(i,i+1),out result))
                {
                    //Not an integer
                    append = false;
                }
            }
    

    如果append为true,则字符串为整数。也许这是一种更巧妙的方法,但这是可行的。

        2
  •  8
  •   Echilon Mafarnakus    13 年前

    在VB.NET中进行编码,以检查字符串是否只包含数值。

    If IsNumeric("your_text") Then
      MessageBox.Show("yes")
    Else
      MessageBox.Show("no")
    End If
    
        3
  •  4
  •   Joel Etherton    16 年前

    使用正则表达式:

    Dim reg as New RegEx("^\d$")
    
    If reg.IsMatch(myStringToTest) Then
      ' Numeric
    Else
      ' Not
    End If
    

    更新:

    如果您在vb.net 2008/2010中执行此任务,也可以使用Linq来完成相同的任务。

    Dim isNumeric as Boolean = False
    
    Dim stringQuery = From c In myStringToTest 
                              Where Char.IsDigit(c) 
                              Select c
    
    If stringQuery.Count <> myStringToTest.Length Then isNumeric = False
    
        4
  •  3
  •   Pierre-Alain Vigeant    16 年前

    如果不想使用regex,只需检查每个字符 char.IsNumber 作品。

    你可以把它和 All 扩展方法(在C_中,我不知道如何用vb.net编写它):

    string value = "78645655";
    bool isValid = value.All(char.IsNumber);
    

    退房其他 char 方法,如 IsDigit .

        5
  •  3
  •   Vanmachin    16 年前

    2其他紧凑型解决方案:

    没有LINQ:

    Dim foo As String = "10004"
    Array.Exists(foo.ToCharArray, Function(c As Char) Not Char.IsNumber(c))
    

    使用Linq(在另一个答案中,只有vb.net相当于c版本):

    foo.All(Function(c As Char) Char.IsNumber(c))
    
        6
  •  2
  •   Andy G    11 年前

    未提及负值,其中 Integer.TryParse 会接受的。

    我更喜欢 UInteger.TryParse 这将拒绝一个负数。但是,如果值以“+”开头,则需要进行附加检查:

    Dim test As String = "1444"
    Dim outTest As UInteger
    If Not test.StartsWith("+") AndAlso UInteger.TryParse(test, outTest) Then
        MessageBox.Show("It's just digits!")
    End If
    

    或 ULong.TryParse 对于更大的数字。

        7
  •  1
  •   Kyra    16 年前

    模式匹配!见 this , this (关于.com)和 this (vb.net开发文章)。

        8
  •  1
  •   Kronass    16 年前

    您可以使用正则表达式或integer.typarse,我更喜欢使用正则表达式检查

        9
  •  1
  •   AllenG    16 年前

    假设您看到的是相对较短的字符串,其数值永远不会大于max int32值,请使用Gage的解决方案。如果长度可变,有时可能溢出,请使用regex( System.Text.RegularExpressions )

    用于检查数字的regex相当常规: ^[0-9]+$

    检查 here 对regex有很好的解释。