【问题标题】:Vb.net get integers only from string with integersVb.net 仅从带有整数的字符串中获取整数
【发布时间】:2012-11-01 22:55:41
【问题描述】:

我有这个字符串123abc123 我怎样才能从这个字符串中只得到整数?

例如,将123abc123 转换为123123

我尝试了什么:

Integer.Parse(abc)

【问题讨论】:

    标签: .net vb.net winforms


    【解决方案1】:

    你可以使用Char.IsDigit

    Dim str = "123abc123"
    Dim onlyDigits = New String(str.Where(Function(c) Char.IsDigit(c)).ToArray())
    Dim num = Int32.Parse(onlyDigits)
    

    【讨论】:

    • VB不支持str.Where(Char.IsDigit)这样的语法吗?
    • @Vlad 在VB中你必须写str.Where(addressOf Char.IsDigit)
    • 有一个错误:'onlyDigits' 没有声明。由于其保护级别,它可能无法访问(谢谢)
    【解决方案2】:

    提取整数的正确方法是使用isNumbric函数:

    Dim str As String = "123abc123"
    Dim Res As String
    For Each c As Char In str
        If IsNumeric(c) Then
            Res = Res & c
        End If
    Next
    MessageBox.Show(Res)
    

    另一种方式:

    Private Shared Function GetIntOnly(ByVal value As String) As Integer
        Dim returnVal As String = String.Empty
        Dim collection As MatchCollection = Regex.Matches(value, "\d+")
        For Each m As Match In collection
            returnVal += m.ToString()
        Next
        Return Convert.ToInt32(returnVal)
    End Function
    

    【讨论】:

    • 再次感谢您。如何将 Res 字符串转换为整数?
    • 这样:Integer.Prase(String)
    • @Nmmmm:也许是Parse?然而,我的拼写检查器建议 Praise.
    • 提醒一句:这个方法做了很多转换......每个字符将被装箱在堆上的一个对象中,以发送到IsNumeric方法,然后将每个数字连接到string 创建一个新的字符串。仅当您知道字符串永远不会很长时,才应该使用这种方式连接字符串,因为字符串越长,速度会非常慢。
    【解决方案3】:
        Dim input As String = "123abc456"
        Dim reg As New Regex("[^0-9]")
        input = reg.Replace(input, "")
        Dim output As Integer
        Integer.TryParse(input, output)
    

    【讨论】:

    • 你不应该忽略TryParse的结果,最好让它崩溃只用Parse。还是 +1
    • 你应该检查输出是否tryparse为真。
    【解决方案4】:

    您可以使用带有模式\D 的正则表达式来匹配非数字字符并将其删除,然后解析剩余的字符串:

    Dim input As String = "123abc123"
    
    Dim n As Integer = Int32.Parse(Regex.Replace(input, "\D", ""))
    

    【讨论】:

      【解决方案5】:

      您还可以使用FindAll 来提取所需的内容。我们还应该考虑使用Val 函数来处理空字符串。

          Dim str As String = "123abc123"
          Dim i As Integer = Integer.Parse(Val(New String(Array.FindAll(str.ToArray, Function(c) "0123456789".Contains(c)))))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-09-14
        • 1970-01-01
        • 2016-01-09
        • 2016-08-26
        • 2019-06-07
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多