Extract Number

kservice

Member
Joined
Jan 13, 2004
Messages
24
I need to extract a number out of a string.

Ex: Session73Number

Should I and could I use a regular expression and if so what would it look like.

In case you cant tell, Ive never written a regular expression. :rolleyes:

Thanks in advance.
 
[0-9]? will determine that any number will be catched.

However... its been a week or two since Ive done Regex... and Im not a master in that section...

Try this :

.*([0-9]?).*

And see .Capture(...) in your regex. It might have captured "73" somewhere. If it didnt... well... keep working... you are on the right track.
 
Dim oldstr As String = "Session73Number"
oldstr = oldstr.Remove(0, 7)
oldstr = oldstr.Remove(2, 6)
MsgBox(oldstr)



That would end you with just 73 ..if that helps any.
 
[0-9]{1,} will match the numbers in your string.

The code below will return an array of all the numbers in your string.

i.e. "Session73Number" will return "73"
"Session73Number532" will return "73" and "532"

Code:
    Public Shared Function ReturnNumericValues(ByVal Text As String) As ArrayList
        Dim myRegExp As New System.Text.RegularExpressions.Regex("[0-9]{1,}", RegexOptions.IgnoreCase)
        Dim Matches As System.Text.RegularExpressions.MatchCollection
        Matches = myRegExp.Matches(Text)
        Dim myMatch As System.Text.RegularExpressions.Match
        Dim matchedValues As New ArrayList

        For Each myMatch In Matches
            matchedValues.Add(myMatch.Value)
        Next

        return matchedValues
    End Function
 
Thanks a bunch I kind of figured out the same thing but your example gives me a much cleaner solution.

Thanks again! :-\
 
Back
Top