[英]Vb.net get integers only from string with integers
我有这个字符串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)))))
在这种情况下,使用 Val() function of vb.net. https://www.hscripts.com/tutorials/v.net/val-function.html 。
Dim str As String = "123abc123"
Dim result As Integer =Val(str)
您还可以使用以下代码:
Public Class Form1
Private Sub Form1_OnLoad() Handles Me.Load
Dim str1 As String = "2,147,4abc83,648" '"123abc123"
FindingNumbers(str1)
End Sub
Private Sub FindingNumbers(ByRef str1 As String)
Dim str2 As String = ""
For i = 0 To str1.Length - 1 Step 1
Dim chr As Char = Mid(str1, i + 1, 1)
Select Case chr
Case "0" : str2 &= "0"
Case "1" : str2 &= "1"
Case "2" : str2 &= "2"
Case "3" : str2 &= "3"
Case "4" : str2 &= "4"
Case "5" : str2 &= "5"
Case "6" : str2 &= "6"
Case "7" : str2 &= "7"
Case "8" : str2 &= "8"
Case "9" : str2 &= "9"
End Select
Next
Try
Dim num As Integer = 0 '(-2,147,483,648 through 2,147,483,647.)
num = CType(str2, Integer)
MsgBox("There was found the following number: " & Str(num), MsgBoxStyle.Information, "Success")
Catch ex As Exception
MsgBox("There was a error in conversion to int from string.", MsgBoxStyle.Exclamation, "Error")
MsgBox("There was found the following number: " & str2, MsgBoxStyle.Information, "Success")
End Try
End Sub
End Class
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.