user1570048
user1570048

Reputation: 880

Parsing numbers out of a string

I have the following string format that can have the following formats

2Y11M23D4H  means Y=2,M=11,D=23,H=4
11Y2M11D19H means Y=11,M=2,D=11,H=19
3Y4H              Y=3,H=4
51H               H=51

I am using vb.net and i want to save the numbers to variables, as you see in the above example each number relates to the variable after it and my problem is I can't find a good way to get the numerical values before a character

I want to find total days as double

The following code only will work with a single digit before each character

 If periodstring.Contains("Y") Then
        totaldays += Convert.ToDouble(periodstring.Substring(periodstring.IndexOf("Y") - 1).First) * 365
    End If

    If periodstring.Contains("M") Then
        totaldays += Convert.ToDouble(periodstring.Substring(periodstring.IndexOf("M") - 1).First) * 30
    End If

    If periodstring.Contains("D") Then
        totaldays += Convert.ToDouble(periodstring.Substring(periodstring.IndexOf("D") - 1).First)
    End If

    If periodstring.Contains("H") Then
        totaldays += Convert.ToDouble(periodstring.Substring(periodstring.IndexOf("H") - 1).First) / 24
    End If

Upvotes: 2

Views: 139

Answers (1)

Mike Dinescu
Mike Dinescu

Reputation: 55720

This is a prime candidate for Regular Expressions. Something like this would work:

Dim rex as RegEx
rex = new RegEx("(\d+)(\w+)")

Dim startPos as Int
Dim m as Match    

startPos = 0
Do
    m = rex.Match(inputString, startPos)
    If(m.Success) Then
        ' m.Groups(1)  will contain the digits
        ' m.Groups(2)  will contain the letter

        startPos = startPos + m.Length
    End if
While(m.Success)

The regex contains two groups: \d+ and \w+. The first group matches a bunch of digits and the second group matches a bunch of letters.

You can match the string for as long as the regex matches and keep extracting the digits group and the letters group. And parse them accordingly..

Check out this simple tutorial here to get a jump start on using the Match class to extract matches using a regular expression in VB.net.

Upvotes: 4

Related Questions