Vb.net 仅从带有整数的字符串中获取整数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13186753/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Vb.net get integers only from string with integers
提问by Usr
I have this string 123abc123how can i get only integers from this string?
我有这个字符串,我 123abc123怎样才能从这个字符串中只获取整数?
For example, convert 123abc123to 123123.
例如,转换123abc123为123123.
What i tried:
我试过的:
Integer.Parse(abc)
回答by Tim Schmelter
You could use Char.IsDigit
你可以用 Char.IsDigit
Dim str = "123abc123"
Dim onlyDigits = New String(str.Where(Function(c) Char.IsDigit(c)).ToArray())
Dim num = Int32.Parse(onlyDigits)
回答by Nmmmm
the right method to extract the integers is using isNumbricfunction:
提取整数的正确方法是使用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)
another way:
其它的办法:
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
回答by urlreader
Dim input As String = "123abc456"
Dim reg As New Regex("[^0-9]")
input = reg.Replace(input, "")
Dim output As Integer
Integer.TryParse(input, output)
回答by Guffa
You can use a regular expression with the pattern \Dto match non-digit characters and remove them, then parse the remaining string:
您可以使用带有模式的正则表达式\D来匹配非数字字符并删除它们,然后解析剩余的字符串:
Dim input As String = "123abc123"
Dim n As Integer = Int32.Parse(Regex.Replace(input, "\D", ""))
回答by NeverHopeless
You can also use FindAllto extract required stuff. we should also consider Valfunction to handle for an empty string.
您还可以使用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)))))

