VB.Net下用正则表达式阻止非法字符输入

2009年04月03日 00:11    发布者:hotpower

    Private Sub TextBox1_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
        Dim ch As Char = e.KeyChar
        If Not Regex.IsMatch(ch.ToString(), "^[\b\r0-9a-fA-F]$") Then
            e.KeyChar = "" '放弃输入的非法字符
            MessageBox.Show("请正确输入16进制数!!!", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error)
        Else
            e.KeyChar = Char.ToUpper(ch) '强制转换为大写字母,放过退格和回车符
        End If
    End Sub

网友评论

alpha321 2010年08月05日
Regex.IsMatch(ch.ToString(), "^[\b\r0-9a-fA-F]$") ,
很典型的应用,不错.
正则表达式功能的确很强大.
陈小东 2010年08月12日
哈哈 支持下
陈小东 2010年08月12日
哈哈 支持下