1

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

例如,转换123abc123123123.

我尝试了什么:

Integer.Parse(abc)
4

5 回答 5

4

你可以使用Char.IsDigit

Dim str = "123abc123"
Dim onlyDigits = New String(str.Where(Function(c) Char.IsDigit(c)).ToArray())
Dim num = Int32.Parse(onlyDigits)
于 2012-11-01T22:58:46.927 回答
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
于 2012-11-01T22:59:00.820 回答
2
    Dim input As String = "123abc456"
    Dim reg As New Regex("[^0-9]")
    input = reg.Replace(input, "")
    Dim output As Integer
    Integer.TryParse(input, output)
于 2012-11-01T23:00:33.413 回答
0

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

Dim input As String = "123abc123"

Dim n As Integer = Int32.Parse(Regex.Replace(input, "\D", ""))
于 2012-11-01T23:12:47.940 回答
0

您还可以使用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)))))
于 2012-11-02T11:02:38.553 回答