阅读量:254
ASP(Active Server Pages)字符是数字,用于在网页中嵌入服务器端脚本。
在ASP中,判断一个字符串是否为数字可以通过多种方法实现,以下是几种常见的方法和示例:

介绍
IsNumeric函数用于判断表达式的值是否为数字,返回布尔值,如果整个表达式被识别为数字,则返回True;否则返回False。
示例代码
Dim MyVar As Object
Dim MyCheck As Boolean
MyVar = "53" ' 赋值
MyCheck = IsNumeric(MyVar) ' 返回 True
Response.Write("The value is numeric: " & MyCheck)
MyVar = "459.95" ' 赋值
MyCheck = IsNumeric(MyVar) ' 返回 True
Response.Write("
The value is numeric: " & MyCheck)
MyVar = "abc123" ' 赋值
MyCheck = IsNumeric(MyVar) ' 返回 False
Response.Write("
The value is numeric: " & MyCheck)
使用正则表达式
介绍
通过正则表达式匹配字符串是否为纯数字或包含小数点的数字。
示例代码
Function IsInteger(input)
Dim oRE, checkletter
Set oRE = New RegExp
oRE.IgnoreCase = True
oRE.Global = True
oRE.Pattern = "^[\d]+$"
IsInteger = oRE.Test(input)
Set oRE = Nothing
End Function
Dim str1, str2, str3
str1 = "123"
str2 = "123.456"
str3 = "abc123"
Response.Write("Is '" & str1 & "' an integer? " & IsInteger(str1) & "
")
Response.Write("Is '" & str2 & "' an integer? " & IsInteger(str2) & "
")
Response.Write("Is '" & str3 & "' an integer? " & IsInteger(str3) & "
")
使用Double.TryParse方法

介绍
Double.TryParse方法尝试将字符串转换为双精度浮点数,如果转换成功则返回True,否则返回False。
示例代码
Function IsNumber(str)
IsNumber = False
If IsNull(str) Or str = "" Then Exit Function
Dim num
On Error Resume Next
num = CDbl(str)
If Err.Number <> Then IsNumber = True
On Error GoTo 0
End Function
Dim testStr1, testStr2, testStr3
testStr1 = "123"
testStr2 = "123.456"
testStr3 = "abc123"
Response.Write("Is '" & testStr1 & "' a number? " & IsNumber(testStr1) & "
")
Response.Write("Is '" & testStr2 & "' a number? " & IsNumber(testStr2) & "
")
Response.Write("Is '" & testStr3 & "' a number? " & IsNumber(testStr3) & "
")
相关问题与解答
问题1:如何在ASP中使用Char.IsNumber()方法来判断字符串是否为数字?
答案:ASP本身不支持Char.IsNumber()方法,但可以在ASP.NET中使用,在ASP中,可以使用类似的逻辑来实现相同功能。
Function IsAllNum(str)
If str == null || str.Length == 0 Then
IsAllNum = False
Exit Function
End If
Dim i, checkletter
For i = 1 To Len(str)
checkletter = Mid(str, i, 1)
If Not IsNumeric(checkletter) Then
IsAllNum = False
Exit Function
End If
Next
IsAllNum = True
End Function
Dim testStr1, testStr2, testStr3
testStr1 = "123"
testStr2 = "123.456"
testStr3 = "abc123"
Response.Write("Is '" & testStr1 & "' all numbers? " & IsAllNum(testStr1) & "
")
Response.Write("Is '" & testStr2 & "' all numbers? " & IsAllNum(testStr2) & "
")
Response.Write("Is '" & testStr3 & "' all numbers? " & IsAllNum(testStr3) & "
")
问题2:如何在ASP中判断一个字符串是否是整数?

答案:可以使用正则表达式来匹配字符串是否为整数,以下是一个示例:
Function IsInteger(input)
Dim oRE
Set oRE = New RegExp
oRE.IgnoreCase = True
oRE.Global = True
oRE.Pattern = "^[\d]+$"
IsInteger = oRE.Test(input)
Set oRE = Nothing
End Function
Dim testStr1, testStr2, testStr3
testStr1 = "123"
testStr2 = "123.456"
testStr3 = "abc123"
Response.Write("Is '" & testStr1 & "' an integer? " & IsInteger(testStr1) & "
")
Response.Write("Is '" & testStr2 & "' an integer? " & IsInteger(testStr2) & "
")
Response.Write("Is '" & testStr3 & "' an integer? " & IsInteger(testStr3) & "
")