C#Masked TextBox,带0或小数

时间:2015-06-23 21:19:19

标签: c# maskedtextbox

用户有一个文本框,他们必须输入0或0.0001到0.9999之间的值。 我可以在这里使用什么正则表达式?我看过其他例子,但看不到这样的事情。

4 个答案:

答案 0 :(得分:1)

我认为这是一个非常有效的解决方案。它允许输入的任何字符串只是'0'或字符串'0'。其次是最多4位数。

        Regex myRegex = new Regex("^(?:(?:0)|(?:0.[0-9]{1,4}))$");
        Console.WriteLine("Regex: " + myRegex + "\n\nEnter test input.");
        while (true)
        {
            string input = Console.ReadLine();
            if (myRegex.IsMatch(input))
            {
                Console.WriteLine(input + " is a match.");
            }
            else
            {
                Console.WriteLine(input + " isn't a match.");
            }
        }

以下是测试列表......

enter image description here

答案 1 :(得分:0)

试试这个:

/(0)+(.)+([0-9])/g

另见东西链接,可能会帮助你建立你赢得了expreession。 http://regexr.com/

答案 2 :(得分:0)

试试这个,它会完成工作,但我没有对所有情况进行测试。

qry.Where(lambda)

注意:输入是一个字符串,在你的情况下Textbox.Text!

答案 3 :(得分:0)

这已准备好使用KeyPress控件的TextBox事件处理程序。它将阻止任何输入,除了0.0001和0.9999之间的数字:

    private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
    {
        //Only one dot is possible
        if ((sender as TextBox).Text.Contains('.') && (e.KeyChar == '.')) e.Handled = true;

        //Only numeric keys are acceptable
        if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && (e.KeyChar != '.')) e.Handled = true;

        //Only one zero in front is acceptable, next has to be dot
        if (((sender as TextBox).Text == "0") && (e.KeyChar == '0')) e.Handled = true;

        double value = 0;
        string inputValue = (sender as TextBox).Text + e.KeyChar;

        if ((sender as TextBox).Text.Length > 0)
        {
            //Just in case parse input text into double
            if (double.TryParse(inputValue, out value))
            {
                //Check if value is between 0.0001 and 0.9999
                if (value > 0.9999) e.Handled = true;
                if (((sender as TextBox).Text.Length > 4) && (value < 0.0001)) e.Handled = true;
            }
        }
        else if (e.KeyChar != '0')
        {
            e.Handled = true;
        }
    }