我正在寻找一个类似于PHP函数is_numeric()的Visual FoxPro函数
我找到了这个,但我不能使用VARTYPE
或TYPE
,因为变量总是一个只包含数字的字符串。
我找到了ISDIGIT()
功能,但手册上说它只检查第一个字符。
确定指定字符的最左边字符表达式是一个数字(0到9)。
ISDIGIT(cExpression)
参数
cExpression指定ISDIGIT()测试的字符表达式。任何cExpression中第一个字符之后的字符将被忽略。
我将使用正则表达式对象VBScript.RegExp
创建自己的函数
FUNCTION isNumeric( tcValue )
LOCAL oRE
oRE = CreateObject("VBScript.RegExp")
oRE.Pattern = '^[0-9]+$'
RETURN oRE.test( tcValue )
ENDFUNC
? isNumeric( '123' )
但是,FoxPro是否为此提供了任何功能
我只是在俯瞰吗?
对于确定字符表达式中最左边的字符是否是字母的ISALHPA()
也是一样的。我想检查变量是否只包含字母。
您可以像这样创建自己的函数。
FUNCTION IsAllDigits
LPARAMETERS tcSearched, tcOptionalSearch
* tcSearched = the string of characters to test.
* tcOptionalSearch = optional, additional characters to allow.
LOCAL lcSearch
m.lcSearch = "01234567989" + IIF(VARTYPE(m.tcOptionalSearch) = "C", m.tcOptionalSearch, "")
LOCAL lcRemaining
m.lcRemaining = CHRTRAN(m.tcSearched, m.lcSearch, "")
RETURN ( LEN(m.lcRemaining) = 0 )
ENDFUNC
这可能适用于ISDIGIT()或ISALPHA()。
Function IsAllDigits(myValue)
lReturn = .t.
FOR i = 1 TO LEN(myvalue)
IF !ISDIGIT( SUBSTR(myValue, i, 1) )
lReturn = .f.
EXIT
ENDIF
ENDFOR
RETURN lReturn
ENDFUNC
FUNCTION ISNUMERIC
LPARAMETERS cVal
LOCAL llNumeric, lnLen, lcChr, lnDecs, lnVal
llNumeric = VARTYPE(cVal) = "N" && Donkey has sent a numeric value
lnDecs = 0
DO CASE
CASE llNumeric
CASE VARTYPE(cVal)<>"C" && Not a character
OTHERWISE
cVal = ALLTRIM(cVal) && Trim spaces
lnLen = LEN(cVal) && How many characters
llNumeric = .T. && Assume
i = 0
DO WHILE llNumeric AND i<lnLen
i = i+1
lcChr = SUBSTR(cVal,i,1) && Get next char
lnVal = VAL(lcChr)
DO CASE
CASE lcChr = "0" && Allowed
CASE lnVal>0 && 1 - 9 OK
CASE INLIST(lcChr, "-", "+") && Allowed but ONLY at the start
llNumeric = i = 1
CASE lcChr = "." && Decimal point but ONLY one
lnDecs = lnDecs+1
llNumeric = lnDecs = 1
OTHERWISE
llNumeric = .F.
ENDCASE
ENDDO
ENDCASE
RETURN llNumeric
ENDFUNC
一行怎么样?
Function IsNumeric
Lparameters pString
Return m.pString == Chrtran(m.pString, Chrtran(m.pString, "0123456789", ""), "")
EndFunc
您可以将任何其他有效字符转换为"0123456789",如"."或",">
测试字符串是否为数字有更简单的方法:
- 如果String="123"=>val('String')>0
- 如果String="AB123"=>val('String')=0
仅此而已。。。
仅使用Visual Fox Pro,您可以执行以下操作:
FUNCTION is_numeric(var_name)
error_trigger=.f. &&** first initialization
&&** evaluate("any_char") will generate an error so I'm using TRY-CATCH-ENDTRY
TRY
EVALUATE(var_name)
CATCH &&** evaluate() generates an error then the string is character
WAIT WINDOW "character"
error_trigger=.t. &&** there was an error returned by evaluate()
EXIT && stop and jump after ENDTRY
ENDTRY
IF error_trigger=.f. &&** there was no error returned by evaluate() then the string was numeric
WAIT WINDOW "numeric"
ENDIF
ENDFUNC
然后调用函数:
is_numeric("333">