March 12, 2009

IsNumeric: More fun with Easy Patterns

Filed under: Scripting — Marcus Tettmar @ 5:14 pm

VBScript has a function called IsNumeric, but as discussed in this forum post VBScript numbers can contain the letter ‘E’ (and it would seem ‘D’ too). These are valid numbers as far as VBScript is concerned but in the real world we usually don’t care for them. Numbers may also be floats. So in the forum post we came up with the following VBScript functions for IsNumber and IsInteger:

VBSTART
Function IsNumber(var)
  IsNumber = (LCase(var) = UCase(var)) and isNumeric(var)
End Function

Function IsInteger(var)
  IsInteger = IsNumber(var) and (InStr(var,".") = 0)
End Function
VBEND

Now we have Easy Patterns I thought I’d show you another neat way to validate that a string is numeric:

//IsNumeric?
Let>data=154.3
RegEx>[lineStart][oneOrMore number or "."][lineEnd],data,1,matches,num_matches,0
If>num_matches>0
  //string IS numeric
Endif

If you just want to check the string is integer, change it to:

//IsInteger?
Let>data=154
RegEx>[lineStart][oneOrMore number][lineEnd],data,1,matches,num_matches,0
If>num_matches>0
  //string IS integer
Endif

If we want to see if a string merely contains a number we can do:

//Contains a number?
Let>data=fred 224 sally 4
RegEx>[oneOrMore number],data,1,matches,num_matches,0
If>num_matches>0
  //string CONTAINS number
Endif