我有这个字符串123abc123
我怎么才能从这个字符串中得到整数?
例如,将123abc123
转换为123123
。
我尝试了什么:
Integer.Parse(abc)
答案 0 :(得分:4)
您可以使用Char.IsDigit
Dim str = "123abc123"
Dim onlyDigits = New String(str.Where(Function(c) Char.IsDigit(c)).ToArray())
Dim num = Int32.Parse(onlyDigits)
答案 1 :(得分: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
答案 2 :(得分: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)
答案 3 :(得分:0)
您可以使用模式\D
的正则表达式匹配非数字字符并删除它们,然后解析剩余的字符串:
Dim input As String = "123abc123"
Dim n As Integer = Int32.Parse(Regex.Replace(input, "\D", ""))
答案 4 :(得分: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)))))