How to find a random number in string


I can't seem to find a way for searching for  random number in a string. for example

"150 Opening BINARY mode data connection.
226 Transfer complete
ftp: 5590252 bytes sent in 9.45Seconds 591.31Kbytes/sec."

I need to find the number that is in bold above which could be a different number every time and be placed in a different position. It will however, always be after  "ftp: ". I then need to assign that number to a variable int.

Can anyone help on this please?

Michael RoodtSenior .NET Integrations DeveloperAsked:
Who is Participating?
käµfm³d 👽Connect With a Mentor Commented:
Try this:
Imports System.Text.RegularExpressions


Dim value As Integer
Dim m As Match = Regex.Match(sourceStr, "(?<=ftp: *)\d+")

If m.Success Then
    value = Convert.ToInt32(m.Value)
    value = -1
End If

Open in new window

Todd GerbertIT ConsultantCommented:
The line doesn't always start with "ftp:"?  i.e., it could sometimes be "Some other stuff ftp: 123345 etc etc"?
Todd GerbertConnect With a Mentor IT ConsultantCommented:
Almost same thing:

Imports System.Text.RegularExpressions
Module Module1

    Sub Main()
        Dim re As New Regex("ftp:\s+(\d+)\b")

        Dim test = "150 Opening BINARY mode data connection.226:    Transfer(complete) ftp: 5590252 bytes sent in 9.45Seconds 591.31Kbytes/sec."

        Dim m = re.Match(test)
        If m.Success Then
            Dim byteCount As Long
            If Int64.TryParse(m.Groups(1).Value, byteCount) Then
                Console.WriteLine("Found number: {0}", byteCount)
            End If
        End If

    End Sub

End Module

Open in new window

käµfm³d 👽Commented:
The one caveat to tgerbert's pattern, and I don't think it will come to play here, is that if the number following "ftp: " were not followed by a space and had a string immediately following it (e.g.  "ftp: 5590252bytes"), then the match would fail due to the use of the word boundary at the end of the pattern. Again, I don't perceive that to be an issue here  = )
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.