textbox1的正则表达式? C# [英] Regular expressions for textbox1 ? C#

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

问题描述

您好,



我可以将textBox1限制为仅接受:数字,大写和 - ?

我想在textBox1中可以只输入:



1.数字(0-9)

2.仅限大写英文

3。 -

(所有其他字符都没有启用)

谢谢。



我有什么试过:



Hello,

Can I limit my textBox1 to only accept: Numbers, Uppercase and -?
I want to in textBox1 can enter only :

1. Numbers (0-9)
2. only Uppercase English
3. -
(all other characters are not enabled)
Thank you.

What I have tried:

private void textBox1_TextChanged(object sender, EventArgs e)
{           
   if (System.Text.RegularExpressions.Regex.IsMatch(textBox1.Text, @"^[a-zA-Z][a-zA-Z0-9\'\'-']))
    {
        
    }
    
}

推荐答案



为什么使用正则表达式?

[edit: added dash]
Why regular expressions?
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    if (!char.IsDigit(e.KeyChar) && !(e.KeyChar >= 'A' && e.KeyChar <= 'Z') && e.KeyChar != '-')
    {
        e.Handled = true;
    }
}



但是,如果你想要正则表达式,请使用\ b [A-Z0- 9] +(?: - [A-Z0-9] +)+


试试这个正则表达式:

Try this regex:
[^a-zA-Z0-9\-]



如果匹配,您的文本框中包含非法字符。

您可以使用Regex.Replace删除它们:


If it matches, your textbox contains an illegal character.
You can use Regex.Replace to remove them:

textBox1.Text = Regex.Replace(textBox1.Text, "[^a-zA-Z0-9\-]", "");

但如果您希望用户满意,您必须小心处理插入位置 - 您可以通过以下方式获取并设置它SelectionStart属性。



不要在TextChanged事件中使用该代码而不检查是否需要它!您将获得无限循环...

But you will have to be careful with the caret position if you want the user to be happy - you can get and set it via the SelectionStart property.

Do not just use that code in the TextChanged event without checking if it's needed! You will get an infinite loop...


使用以下代码添加 KeyPress 事件处理程序:

Add a KeyPress event handler, with this code:
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    if (e.KeyChar != (char)Keys.Back && !char.IsDigit(e.KeyChar) && !char.IsUpper(e.KeyChar) && e.KeyChar != '-')
    {
        e.Handled = true;
    }
}



如何工作:如果char不是退格而不是数字而不是大写字母而不是 - ,然后 e.Handled 设置为true,这意味着该事件将被视为'已处理'并且赢得了char不要添加到文本框中。


How this works: if the char is not a backspace and not a digit and not an uppercase letter and not a -, then e.Handled is set to true, which means that the event will be considered 'handled' and the char won't be added to the textbox.


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

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