选中包含任何字符和数字的文本框

本文关键字:数字 文本 字符 包含任 何字符 | 更新日期: 2023-09-27 18:28:01

我想让用户输入的文本框中的文本必须包含字符和数字。示例:A1001。我已经使用Regex找到了一个解决方案,如果文本框中不包含后跟数字的字符,则会显示一个错误消息框,但一旦我在文本框中输入文本"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);
            }
        }

非常感谢您的回答!

感谢

选中包含任何字符和数字的文本框

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

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]+

由于我假设您只想在该字段中输入产品代码,我还添加了^作为字符串的开头和$作为字符串的结尾。

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

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

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

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

L0000

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

例如LLL-000会给您3个字母,后面跟着一个缩进和3个数字。

您的问题似乎有点令人困惑。请在按钮内点击尝试

        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);
        }