Purpose |
Extracts a number part of
a string
|
Author | Date of code (original) | Updated on | Date of page (original) | Updated on |
Tim Nuteson Tim.Nuteson@target.com |
07June2002
|
|
07June2002
|
|
Restrictions on use |
This module is distributed under the terms of the Lesser GNU General
Public License. Restrictions on the use of this work in a commercial
application or derivative work is described in the Lesser GNU General
Public License page at:
http://www.fsf.org/copyleft/lesser.html
|
Description |
ExtractNumber$() finds in a string the numeric characters that forms a number. The "number" should be preceded by a space and followed by a space or the end of the string. The "number" can be an integer or a decimal number as long as it contains a leading digit (zero or non-null). Only the first "number" of a string is extracted. Designed originally for parsing
out highway numbers for display in highway shields
|
External resources |
none
|
Declare statement of sub_function. Include in your program. Copy/Paste if needed. |
Declare
function ExtractNumber$ (byval Str as string) as String
|
Returned value(s) (function only) |
a string of characters
forming a number. The string is empty if no number is found.
|
Other required declare statement(s). Include in your program. Copy/Paste if needed. |
|
MapBasic Code. Copy/Paste if needed.
|
Function ExtractNumber$(Byval Str as String) as String
Dim SubStr as String Dim numpos, spacepos, checkpos as SmallInt
For checkpos = 1 to Len(str) If Mid$(str, checkpos, 1) = any("1", "2", "3", "4", "5", "6", "7", "8", "9", "0") ThenNumPos = checkpos Exit For End If Next
If NumPos then SpacePos = Instr(numpos, Str, " ") End If
If Spacepos then SubStr = Mid$(str, numpos, spacepos-numpos) Else SubStr = Mid$(str, numpos, len(str) - numpos + 1) End If
ExtractNumber$ = SubStr
End Function |
Availability for download |
Example |
dim result as string result = extractnumber$("Are we in 2002 or not?") if result ="" then print "No number in string" else print val(result) end if |
|
Comments |
1 - If a decimal number could
start with a 'point', i.e. without leading digit, the code should be
modified by adding "." to the list of ANY( ).
2 - If there are more than one
number in the string, that string should be repeatedly truncated and
processed with the function as long as a number is found.
|
See also |