正则表达式编号验证 [英] Regular expression number validation

查看:274
本文介绍了正则表达式编号验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用正则表达式来验证文本框条目(类似:^(?! 0 $)([0-9] | 1 [0-8])(\.5 )?$).有效条目是介于0.5到18之间的数字,增量为0.5.

I am trying to use a regular expression to validate a text box entry (Something like: ^(?!0$)([0-9]|1[0-8])(\.5)?$). Valid entries are numbers between 0.5 and 18 with an increment of 0.5.

有效:0.5、1、1.5 、. . . ,17.5、18

Valid: 0.5, 1, 1.5, . . . , 17.5, 18

无效:...,-1、0、18.5 、. .

Invalid: ..., -1, 0, 18.5, . . .

谢谢!

推荐答案

 您只需对文本框中的文本进行几次标准检查即可完成此操作,而不必使用RegEx.当您需要检查字符串中的复杂模式时,通常使用正则表达式.下面的示例将确保文本字符串 是有效的Double类型数字,并且它是0.5的偶数增量,大于或等于0.5,但是,不大于18.

 You could do this with just a couple standard checks on the text in the textbox instead of using RegEx.  Regex is usually used when you need to check for complex patterns in a String.  The below example will make sure that the text string is a valid Double type number and that it is an even increment of 0.5 that is greater than or equal to 0.5 but,  not greater than 18.

Public Class Form1

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim dbl As Double = 0.0

        If Double.TryParse(TextBox1.Text, dbl) AndAlso dbl >= 0.5 AndAlso dbl <= 18.0 AndAlso dbl Mod 0.5 = 0 Then

            'do something with the (dbl) value....

        Else
            MessageBox.Show("You have entered an invalid number.")
        End If
    End Sub

End Class


这篇关于正则表达式编号验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆