![](/img/trans.png)
[英]Regular expression for allowing a user to enter alphanumeric characters and only one non-alphanumeric character
[英]how to restrict a user to enter only single character i.e “Y” and “N” using a regular expression
我试图限制用户输入单个字符,即“ Y”或“ N”,除此之外没有其他内容。 我尝试了以下正则表达式,但它不起作用:
^(Y | N){1} $
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
Regex r = new Regex(@"^(Y|N){1}$");
r.IsMatch(textBox1.Text);
}
我使用的正则表达式无法正常工作。 如何限制用户输入只能是“ Y”或“ N”的单个字符
您可以尝试使用以下正则表达式:^ [YN] $
它将仅与字符Y和N匹配,如果需要,您还可以添加更多字符。
如果您愿意放弃正则表达式,则可以执行以下操作之一:
必须为单个字符(任何单个字符):
if (textBox1.Text.Length == 1)
必须是单个字符Y
或N
if (new[] { "Y", "N" }.Contains(textBox1.Text))
如果必须使用正则表达式,那么Vivek的建议既好又简单:
if (new Regex(@"^[YN]$").IsMatch(textBox1.Text))
请记住,如果您只关心KeyPress
, 用户仍然可以用鼠标右键单击在其中粘贴一些文本 。 我不会为此使用TextBox
,但是如果您真的那样喜欢,我会改用另一个事件:
private void textBox1_TextChanged(object sender, EventArgs e)
{
string text = ((TextBox)sender).Text.ToUpper();
if (text.Length > 1)
text = text.Substring(0, 1);
if (text != "Y" && text != "N")
text = "";
((TextBox)sender).Text = text;
}
这样,您总是在文本框中获得大写的Y
或N
,并且用户可以轻松更改该值,而无需按Backspace键。
你为什么很难?
if(textBox1.Text.Equals("Y") || textBox1.Text.Equals("N"))
该代码不完整。 您可能需要某种条件才能实际执行限制:
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
Regex r = new Regex(@"^(Y|N){1}$");
if (r.IsMatch(textBox1.Text)==false) {
//do something, like popping an alert or making e.Handled = true to cancel the event.
}
}
至于要使用的正则表达式,您应该使用它(或者您可以使用其他用户提出的建议之一)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.