实现:C#窗体中的文本框只能输入中文汉字,其他输入无效。问:正则表达式怎么用?

时间:2023-03-10 01:59:18
实现:C#窗体中的文本框只能输入中文汉字,其他输入无效。问:正则表达式怎么用?

原文:实现:C#窗体中的文本框只能输入中文汉字,其他输入无效。问:正则表达式怎么用?

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)

        {

            Regex rg = new Regex("^[\u4e00-\u9fa5]$");

            if (!rg.IsMatch(e.KeyChar.ToString()) && e.KeyChar != '\b') //'\b'是退格键

            {

                e.Handled = true;

            }

        }

或者

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)

        {

            Regex rg = new Regex("^[\u4e00-\u9fa5\b]$"); //\b是退格键

       if (!rg.IsMatch(e.KeyChar.ToString()))

            {

                e.Handled = true;

            }

        }

文本框只能输入汉字,字母、数字、符号、空格键入无效,退格能用,完全实现了。非常感谢!

转自:http://zhidao.baidu.com/question/421426815.html