检查文本框中是否包含任何字符和数字

时间:2014-10-28 08:02:31

标签: c# regex winforms

我想在用户输入的文本框中的文本所在位置,必须包含后跟数字的字符。示例:A1001。我已经找到了使用正则表达式的解决方案并显示错误消息框如果文本框不包含字符后跟数字,但是一旦我输入文本" A1"在文本框中,仍会显示错误消息框。

以下是我正在使用的代码:

void button1_Click(object sender, EventArgs e)
        {
            if (!Regex.IsMatch(this.textBox1.Text, @"(a-zA-Z)"))
            {
                SystemManager.ShowMessageBox("Please enter the characters followed by the numbers for the product code. \nExample: A1001", "Information", 2);
            }

            else if (!Regex.IsMatch(this.textBox1.Text, @"(0-9)"))
            {
                SystemManager.ShowMessageBox("Please enter the characters followed by the numbers for the product code. \nExample: A1001", "Information", 2);
            }
        }

非常感谢您的回答!

谢谢

4 个答案:

答案 0 :(得分:2)

对整个表达式使用一个正则表达式:

if (!Regex.IsMatch(this.textBox1.Text, @"^[a-zA-z][0-9]+$"))
{
  SystemManager.ShowMessageBox("Please enter the characters followed by the numbers for the product code. \nExample: A1001", "Information", 2);
}

这将匹配一个字符后跟一个或多个数字的字符串。如果您想允许多个字符,则必须使用[a-zA-z]+

由于我假设您只想在此字段中输入产品代码,我还添加了^ for start和$ for the string。

答案 1 :(得分:1)

^[a-zA-Z]+\d+$

试试这个。这个正则表达式将验证您的条件。参见演示。

http://regex101.com/r/sU3fA2/25

答案 2 :(得分:1)

在表单中,您还可以使用MaskedTextbox,使用此控件并将Mask属性设置为:

L0000

这样,您可以强制用户输入一个字母(L)和4个数字(0000)。当然,您可以按照自己的方式进行自定义。

例如,LLL-000将为您提供3个字母,后跟缩进和3个数字。

答案 3 :(得分:0)

你的问题似乎有点令人困惑。 请在按钮内单击

        if (!Regex.IsMatch(this.MyTextBox.Text, @"[A-C][0-9]{4}"))
        {
            SystemManager.ShowMessageBox("Please enter the characters followed by the numbers for the product code. \nExample: A1001", "Information", 2);
        }
相关问题