我有这个字符串我 123abc123
怎样才能从这个字符串中只得到整数?
例如,转换123abc123
为123123
.
我尝试了什么:
Integer.Parse(abc)
你可以使用Char.IsDigit
Dim str = "123abc123"
Dim onlyDigits = New String(str.Where(Function(c) Char.IsDigit(c)).ToArray())
Dim num = Int32.Parse(onlyDigits)
提取整数的正确方法是使用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
Dim input As String = "123abc456"
Dim reg As New Regex("[^0-9]")
input = reg.Replace(input, "")
Dim output As Integer
Integer.TryParse(input, output)
您可以使用带有模式的正则表达式\D
来匹配非数字字符并删除它们,然后解析剩余的字符串:
Dim input As String = "123abc123"
Dim n As Integer = Int32.Parse(Regex.Replace(input, "\D", ""))
您还可以使用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)))))