'Vb.net get integers only from string with integers

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)


Solution 1:[1]

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)

Solution 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)

Solution 3:[3]

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", ""))

Solution 4:[4]

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)))))

Solution 5:[5]

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)

Solution 6:[6]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Tim Schmelter
Solution 2 urlreader
Solution 3 Guffa
Solution 4 NeverHopeless
Solution 5 Karthik Karnam
Solution 6 purple_2022