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", ""))
Related videos on Youtube
Comments
-
Usr almost 2 years
I have this string
123abc123
how can i get only integers from this string?For example, convert
123abc123
to123123
.What i tried:
Integer.Parse(abc)
-
Vlad over 11 yearsdoesn't VB support syntax like
str.Where(Char.IsDigit)
? -
Magnus over 11 years@Vlad In VB you would have to write
str.Where(addressOf Char.IsDigit)
-
Usr over 11 yearsthere is a error : 'onlyDigits' is not declared. It may be inaccessible due to its protection level (thank you to)
-
Usr over 11 yearsthank you again. how can i convert the Res string to integer number?
-
Vlad over 11 yearsyou ought to not ignore the result of
TryParse
, better let it crash with justParse
. still +1 -
urlreader over 11 yearsyou are supposed to check the output whether the tryparse is true.
-
Nmmmm over 11 yearsin this way: Integer.Prase(String)
-
Vlad over 11 years@Nmmmm: perhaps
Parse
? My spellchecker suggests howeverPraise
. -
Guffa over 11 yearsA 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.