Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to find a Number In a String 1

Status
Not open for further replies.

campbere

Technical User
Oct 10, 2000
146
0
0
US
I am trying to determine how I can find numbers in a string.

For example if I had the string:

Trying to figure out how to do this in less than 123 steps. Help please.

I would like to return 123 to a variable.

Can Someone help?
 
There are a lot of ways to do it. One that pops to my mind is looping through the string a character at a time and checking to see if it is numeric and holding those that are. You may also want to keep track of whether or not they are in a row or seperated by other non-numeric characters, etc.
 
I can think of two approaches right off

1) The Brute Force Approach using the Split Function

InLine = "Trying to figure out how to do this in less than 123 steps. Help please."
Tokens = Split(InLine, " ")
For idx = 0 To UBound(Tokens) - 1
If (Val(Tokens(idx)) > 0) Then
TheNumber = Tokens(idx)
Exit For
End If
Next idx

2) Using the Regular Expression Object. You'll need to add a reference to the Microsoft VBScript Regular Expressions into the project

InLine = "Trying to figure out how to do this in less than 123 steps. Help please."
Set lReg_RegExp = New RegExp
lReg_RegExp.Pattern = "^.*\s(\d+)\s.*"
TheNumber = lReg_RegExp.Replace(lStr_InLine, "$1")

Good Luck
--------------
As a circle of light increases so does the circumference of darkness around it. - Albert Einstein


 
Try this function, there's no need for loops, or brute force!


Private Function FindNumber(ByVal Msg As String, ByVal
Search As Long) As Long

Dim Found As Long

Found = InStr(1, Msg, CStr(Search))

If (Found <> 0) Then
FindNumber = CLng(Mid(Msg, Found, Len(CStr(Search))))
Else
FindNumber = &HFFFF
End If

End Function


Just pass a string to the function and a number to search for..

Example:


Dim Ret As Long

Ret = FindNumber(&quot;Trying to figure out how to do this in
less than 123 steps.&quot;, 123)


FindNumber will return the number you passed it, if it was found, if the number was not found it will return -1 or &HFFFF. In this case it will return 123.

Best Regards,
Nathan Martini
Advanced Computer Solutions
 
Thank you everyone for all the ideas. I will try them out and see which one works best for me.

Thanks again.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top