[RESOLVED] Get number out of a string
Hi there,
as the title says i try to get a number out of a string.
Like in:
"3.1 Ram test"
i try to get out the 3.1
But the length of the number is not always the same. it could be like
"3 Ram Test"
"3.1 Ram Test"
"3.11 Ram Test"
etc.
I thought there was something like val() but that doesnt work in vb.net.
And the last thing is - there could b another number in that string, like
"3.1 Ram Test 1"
but i just want to have the 3.1
Any suggestions??
Thanx.
Fred
Re: Get number out of a string
Is there always a space between the number that you want and the first word?
vb.net Code:
Dim str As String = "3.11 Ram Test"
Dim tmp() As String = str.Split(" "c)
MessageBox.Show(tmp(0))
Re: Get number out of a string
This is one of those cases where a Runtime function can add value:
vb.net Code:
Dim str As String = "3.11 Ram Test"
Dim num As Double = Val(str)
MessageBox.Show(num.ToString())
This will, of course, only work if the number is at the start of the string.
Re: Get number out of a string
VB.NET Code:
Imports System.Text.RegularExpressions
' ...
MessageBox.Show((New Regex("((\d+)\.(\d+))")).Match("3.11 Ram Test").Value)
Re: Get number out of a string
Thanx for the answers.
since the number will always be at the begining of the string jmcilhinneys method works perfect.
But the others are also good to know.
Fred