vb.net 仅限 Visual Basic 正则表达式数字
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17432041/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Visual Basic RegularExpression Digits only
提问by eidsonator
I should preface this by stating that Visual Basic is not my native language, but I am maintaining a legacy program until which time it can be ported to a different language.
我应该先声明 Visual Basic 不是我的母语,但我正在维护一个遗留程序,直到它可以移植到不同的语言为止。
We have a Textbox that is used to enter a quantity. This quantity should be whole numbers only, and this was not being validated. A decimal sneaked into the database and I've been asked to add validation of input. I have tried a Regular Expression.
我们有一个用于输入数量的文本框。这个数量应该只是整数,这没有得到验证。一个小数潜入数据库,我被要求添加输入验证。我试过正则表达式。
Function validate_qty(qty As String)
Dim objRegExp As New System.Text.RegularExpressions.Regex("^\d+$")
Dim match As System.Text.RegularExpressions.Match = objRegExp.Match(qty)
If match.Success Then
Return True
End If
Return False
End Function
This is working as far as decimal points is concerned: .1and 1.0return false; however, alphanumeric strings such as a1212or 433498ereturn True
就小数点而言,这是有效的:.1并1.0返回 false;但是,字母数字字符串,例如a1212或433498e返回True
Any insight? It would be greatly appreciated.
任何见解?这将不胜感激。
回答by freefaller
Other than shortening the function, I can't see a problem with your RegEx...
除了缩短函数之外,我看不出你的 RegEx 有什么问题......
Private Function validate_qty(Byval qty As String) As Boolean
Dim objRegExp As New System.Text.RegularExpressions.Regex("^\d+$")
Return objRegExp.Match(qty).Success
End Function
Another option would be to use the static Integer.TryParse...
另一种选择是使用静态Integer.TryParse...
Private Function validate_qty(Byval qty As String) As Boolean
Return Integer.TryParse(qty, Nothing)
End Function
回答by matzone
I dont think you need regex yet ..
我认为你还不需要正则表达式..
Function validate_qty(qty As String) As Boolean
if qty.Contains(".") then Return False
Return IsNumeric(qty)
End Function
回答by keyboardP
You could create a function which returns a "cleaned" string (i.e. one that has any non-digits removed)
您可以创建一个返回“已清理”字符串的函数(即删除了任何非数字的字符串)
Public Function KeepNumbers(input As String) As String
Dim sb As New StringBuilder()
For Each c As Char In input
If [Char].IsDigit(c) Then
sb.Append(c)
End If
Next
Return sb.ToString()
End Function
回答by Monwabisi
I also do not see where your error might be on your regex
我也没有看到你的错误可能在你的正则表达式上
but try.
但是试试吧。
btnSave/formload()
dim num as new regex("^\d+$")
if num.Ismatch(yourtextbox1.text) then
yourtextbox1.text="num"
else
yourtextbox.text="invalid num"
exit sub
end if
after this you accept if its correct or terminate by "exit sub " if its incorrect.
在此之后,如果正确则接受,如果不正确,则以“exit sub”终止。

