Validation 将字符串验证为正整数

Validation 将字符串验证为正整数,validation,vbscript,Validation,Vbscript,我试图解决一个非常常见的问题-验证输入是否为大于1的正整数。到目前为止,只要输入的不是科学符号,我所尝试的方法就有效 我花了很长时间寻找解决方案,但没有找到任何具体的案例。这是我目前的代码: If IsNumeric(objArgs(1)) Then If CLng(objArgs(1)) = objArgs(1) Then if(objArgs(1) < 1) then wscript.echo "2nd parameter must be greater th

我试图解决一个非常常见的问题-验证输入是否为大于1的正整数。到目前为止,只要输入的不是科学符号,我所尝试的方法就有效

我花了很长时间寻找解决方案,但没有找到任何具体的案例。这是我目前的代码:

If IsNumeric(objArgs(1)) Then

  If CLng(objArgs(1)) = objArgs(1) Then
    if(objArgs(1) < 1) then
      wscript.echo "2nd parameter must be greater than 1"
    else
      ' move on
    end if
  else
    wscript.echo "2nd parameter is not an integer"
  end if
  else
    wscript.echo "2nd parameter is not numeric"      
end if
如果是数字(objArgs(1)),则
如果CLng(objArgs(1))=objArgs(1),则
如果(objArgs(1)<1),则
wscript.echo“第二个参数必须大于1”
其他的
“继续
如果结束
其他的
wscript.echo“第二个参数不是整数”
如果结束
其他的
wscript.echo“第二个参数不是数字”
如果结束
当输入类似于
a
0
-10
3.14
等时,这种方法可以正常工作

我的问题发生在我在科学记数法中输入一个(大)数字时,比如
1E+48
。如果输入此值,则
CLng()
-函数会出现溢出错误


如何避免这种情况?

CLng将转换为long,最大值为2^31-1。 如果你想测试真正的大数和/或分数, 使用CDbl(转换为双精度)

或者你真的想引用一个非常大但仍然是整数的非标准类?(即整数>2^31-1)

正在验证输入是否为大于1的正整数

像这样的验证任务是正则表达式的领域

Function IsPositiveInteger(input)
  Dim re : Set re = New RegExp

  re.pattern = "^\s*0*[1-9]\d*\s*$"
  IsPositiveInteger = re.test(input)
End Function
用法:

MsgBox IsPositiveInteger("asdf")   ' False
MsgBox IsPositiveInteger("0000")   ' False
MsgBox IsPositiveInteger("0001")   ' True
MsgBox IsPositiveInteger("9999")   ' True
支出

^       # start of string
\s*     # allow any number of leading spaces
0*      # allow any number of leading zeros
[1-9]   # require one digit between 1 and 9
\d*     # allow any number of following digits
\s*     # allow any number of trailing spaces
$       # end of string
这将识别任何符合正整数条件的字符串。它不允许您查看字符串表示的整数是否适合VBScript的数值数据类型之一

如果脚本需要这样的转换,则必须自己应用范围检查。这很容易通过字典字符串比较来实现


要获得更严格的结果,请删除表达式中允许前导/尾随空格的部分。

感谢您提供的解决方案,尤其是此详细答案,包括对表达式的解释@如果你想允许科学记数法,我必须改变表达方式。不,我不想允许,一切都很好:)