Reputation: 59
I have this string 123abc123
how can i get only integers from this string?
For example, convert 123abc123
to 123123
.
What i tried:
Integer.Parse(abc)
Upvotes: 2
Views: 16534
Reputation: 83
you also can use the following code:
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
Upvotes: 0
Reputation: 168
In this case, Use Val() function of vb.net. https://www.hscripts.com/tutorials/vbnet/val-function.html.
Dim str As String = "123abc123"
Dim result As Integer =Val(str)
Upvotes: 0
Reputation: 11233
You can also use FindAll
to extract required stuff. we should also consider Val
function to handle for an empty string.
Dim str As String = "123abc123"
Dim i As Integer = Integer.Parse(Val(New String(Array.FindAll(str.ToArray, Function(c) "0123456789".Contains(c)))))
Upvotes: 0
Reputation: 187
the right method to extract the integers is using isNumbric
function:
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
Upvotes: 3
Reputation: 700362
You can use a regular expression with the pattern \D
to match non-digit characters and remove them, then parse the remaining string:
Dim input As String = "123abc123"
Dim n As Integer = Int32.Parse(Regex.Replace(input, "\D", ""))
Upvotes: 1
Reputation: 6605
Dim input As String = "123abc456"
Dim reg As New Regex("[^0-9]")
input = reg.Replace(input, "")
Dim output As Integer
Integer.TryParse(input, output)
Upvotes: 2
Reputation: 460138
You could use Char.IsDigit
Dim str = "123abc123"
Dim onlyDigits = New String(str.Where(Function(c) Char.IsDigit(c)).ToArray())
Dim num = Int32.Parse(onlyDigits)
Upvotes: 4