正则表达询问它 [英] Regular Expression ask about it

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

问题描述

我有一个由按键处理的文本框。我希望文本框必须只接受字母,数字并允许他按退格键。



我该怎么办?



但退格不起作用



感谢您的快速回复



谢谢

I have a textbox that is handled by a keypress. I want the textbox must accept only alphabet, numbers and allowing him to press the backspace.

how can i do it ?

but the backspace does not work

thanks for any fast reply

THANKS

推荐答案

我首先处理TextBox的TextChanged事件 - 忽略键事件,因为它们仍会允许通过粘贴(表单键盘或鼠标)中的不需要的数据。



在TextChanged事件中,用空字符串替换所有不需要的字符。

I would start by handling the TextChanged event for the TextBox - ignore the key events, as they will still allow unwanted data in via Paste (form keyboard or mouse).

In the TextChanged event, replace all unwanted characters with empty strings.
private void MyTextBox_TextChanged(object sender, EventArgs e)
    {
    TextBox tb = sender as TextBox;
    if (tb != null)
        {
        string original = tb.Text;
        string revised = Regex.Replace(original, "[^\\w]", "");
        if (original != revised)
            {
            int cursor = tb.SelectionStart;
            tb.Text = revised;
            tb.SelectionStart = cursor;
            }
        }
    }


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

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