Vb.net get integers only from string with integers

15,212

Solution 1

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

Solution 2

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 3

    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 4

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", ""))
Share:
15,212

Related videos on Youtube

Usr
Author by

Usr

=)

Updated on June 04, 2022

Comments

  • Usr
    Usr almost 2 years

    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)
    
  • Vlad
    Vlad over 11 years
    doesn't VB support syntax like str.Where(Char.IsDigit)?
  • Magnus
    Magnus over 11 years
    @Vlad In VB you would have to write str.Where(addressOf Char.IsDigit)
  • Usr
    Usr over 11 years
    there is a error : 'onlyDigits' is not declared. It may be inaccessible due to its protection level (thank you to)
  • Usr
    Usr over 11 years
    thank you again. how can i convert the Res string to integer number?
  • Vlad
    Vlad over 11 years
    you ought to not ignore the result of TryParse, better let it crash with just Parse. still +1
  • urlreader
    urlreader over 11 years
    you are supposed to check the output whether the tryparse is true.
  • Nmmmm
    Nmmmm over 11 years
    in this way: Integer.Prase(String)
  • Vlad
    Vlad over 11 years
    @Nmmmm: perhaps Parse? My spellchecker suggests however Praise.
  • Guffa
    Guffa over 11 years
    A word of caution: This method does a lot of conversion... Each character will be boxed in an object on the heap to be sent to the IsNumeric method, then concatenating each digit to the string creates a new string. Concatenating strings that way should only be used when you know that the strings can never be long, as it gets tremendously slow with longer strings.