【发布时间】:2012-11-01 22:55:41
【问题描述】:
我有这个字符串123abc123 我怎样才能从这个字符串中只得到整数?
例如,将123abc123 转换为123123。
我尝试了什么:
Integer.Parse(abc)
【问题讨论】:
我有这个字符串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)
【讨论】:
str.Where(Char.IsDigit)这样的语法吗?
str.Where(addressOf Char.IsDigit)
提取整数的正确方法是使用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
【讨论】:
Parse?然而,我的拼写检查器建议 Praise.
IsNumeric方法,然后将每个数字连接到string 创建一个新的字符串。仅当您知道字符串永远不会很长时,才应该使用这种方式连接字符串,因为字符串越长,速度会非常慢。
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
您可以使用带有模式\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)))))
【讨论】: