Question remove letters from String and then convert to Integer

msvhub

Member
Joined
Dec 14, 2009
Messages
5
Programming Experience
1-3
Hi,

my problem is, I would like to convert a String into an Integer.

My String is filled with one- or two digit numbers, letters and characters, e.g.:

Dim a As String = "9AB_C"
Dim b As String = "abc_22xyz"
Dim c As Integer
Dim d As Integer

b should have the value "9"
d should have the value "22"

What can I do? The split-function only cuts the string... I would like to read it and get rid of everything except the numbers.

Thank you!
 
You can for example do a single Regex match for repeating numeric chars:
VB.NET:
Dim d As Integer = CInt(Regex.Match(b, "\d+").Value)
 
VB.NET:
	Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
		Dim a As String = "9AB_C"
		Dim b As String = "abc_22xyz"
		Dim c As Integer = StripAlpha(a)
		Dim d As Integer = StripAlpha(b)
	End Sub

	Private Function StripAlpha(ByVal inputString As String) As Integer
		Return CInt(Regex.Replace(inputString, "[^\d]", String.Empty))
	End Function

Edit: Doh, teach me to do real work in the middle of answering a question.
 
Last edited:
VB.NET:
		Dim message As String = "we45ty789qas2"
		Dim msgn As String = ""
		For Each ch As Char In message
			If Char.IsDigit(ch) Then
				msgn &= ch
			End If
		Next ch
		MessageBox.Show("Your numbers-only string is:  " & msgn)
 
Back
Top