【问题标题】:C# entry validation regexC# 条目验证正则表达式
【发布时间】:2011-12-09 17:58:00
【问题描述】:

我刚开始学习 C#。抱歉这个菜鸟问题。

我的第一个培训应用程序是您输入年龄并将其输出到消息框中的应用程序。

我想使用 Regex 验证输入,以便输入字母会引发错误。

问题是我不能让它接受正则表达式。

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            string age;
            age = textBox1.Text;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string regexpattern;
            regexpattern = "^\t+";
            string regex1;

            regex1 = Regex.IsMatch(regexpattern);

            if (textBox1.Text == regex1)
            {             
                MessageBox.Show("error, numbers only please!");
            }         
            else
            {
                string age;
                string afe;
                string afwe2;

                afe = "You are ";
                age = textBox1.Text;
                afwe2 = " years old!";

                MessageBox.Show(afe + age + afwe2);
            }
        }

谢谢!

【问题讨论】:

  • 为什么投票关闭这个过于本地化?这是一个完全有效的 C#/Regex 问题。
  • 试试这个正则表达式 \d+
  • 你不能让它接受是什么意思?如果您的意思是数字也显示错误,那是因为您的正则表达式错误。你可能想要@"^\d+$" 之类的东西。
  • 如果我是你,我会开始用正则表达式以外的东西来学习 C#。您似乎还不太了解类型的工作原理,您需要先了解这一点,然后才能了解 C# 的任何地方。尽管 regex 看起来很简单,但你可能会犯很多错误。

标签: c# regex winforms


【解决方案1】:

你的正则表达式必须是

regexpattern = "^\d+$"; 

编辑 而且编码是错误的。它必须是这样的:

var regex = new Regex(@"^\d+$");

if (!regex.IsMatch(textBox1.Text))
{
    MessageBox.Show("error, numbers only please!");
}

【讨论】:

  • 这不会编译。您需要转义反斜杠或使用逐字字符串。
  • @JustinMorgan:感谢您提及这一点。我已经在网络浏览器中进行了编辑...我已经更正了示例。
【解决方案2】:

正则表达式库是任何开发人员的绝佳资源。您正在寻找的内容可能已经发布在那里。例如,您可能希望将年龄限制在某个范围之间。

regex library

【讨论】:

  • 另外,regexbuddy.com 。一个非常棒的工具,可以即时处理正则表达式。
【解决方案3】:

您不需要正则表达式,只需检查它是否为数字: 这是一个示例代码,希望它可以工作。

private void button1_Click(object sender, EventArgs e)
{
    string age = textBox1.Text;
    int i = 0; // check if it is a int
    bool result = int.TryParse(age, out i) // see if it is a int
    if(result == true){ // check if it is a int
        string afe;
        string afwe2;
        afe = "You are ";
        afwe2 = " years old!";
        MessageBox.Show(afe + age + afwe2);
    } else {
        MessageBox.Show("Please Enter a Number!"); // error message
    }
}

【讨论】:

  • 是的,但我没有想到 :(,不过建议很好。
【解决方案4】:

使用正则表达式

不需要+\d 来验证人的年龄。 一个人通常生活在0 / 113 之间。 :)

if(Regex.IsMatch(age, @"^\d{0,3}"))

其他方法:

使用int.TryParse

int AgeAsInt; 
if(int.TryParse(age, out AgeAsInt)) 

使用 linq

if(!String.IsNullOrEmpty(age) && age.All(char.IsDigit))

如我所愿

if (int.TryParse(age, out ageAsInt) && ageAsInt <= 113)

你可以用想要它。就个人而言,我更喜欢最后一个。

【讨论】:

    猜你喜欢
    • 2012-01-31
    • 2011-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-07
    • 1970-01-01
    • 2010-11-24
    • 1970-01-01
    相关资源
    最近更新 更多