Solved

# How to find a random number in string

Posted on 2011-02-25
424 Views
Hi,

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?

Thanks
0
Question by:Michael Roodt
• 2
• 2

LVL 33

Expert Comment

ID: 34983603
The line doesn't always start with "ftp:"?  i.e., it could sometimes be "Some other stuff ftp: 123345 etc etc"?
0

LVL 74

Accepted Solution

käµfm³d   👽 earned 250 total points
ID: 34983606
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)
Else
value = -1
End If
``````
0

LVL 33

Assisted Solution

Todd Gerbert earned 250 total points
ID: 34983648
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
``````
0

LVL 74

Expert Comment

ID: 34983698
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  = )
0

## Featured Post

Just a quick little trick I learned recently.  Now that I'm using jQuery with abandon in my asp.net applications, I have grown tired of the following syntax:      (CODE) I suppose it just offends my sense of decency to put inline VBScript on a…
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be \$37.1B.
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…