PreviewTextInput中的正则表达式:仅介于0.0到1.0之间的小数 [英] Regex in PreviewTextInput: only decimals between 0.0 and 1.0

查看:134
本文介绍了PreviewTextInput中的正则表达式:仅介于0.0到1.0之间的小数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个正则表达式,它只允许在文本框中输入介于0.0和1.0之间的数字。

I'd like to have a regex, which only allows digits between 0.0 and 1.0 in a textbox.

但是它应该在PreviewTextInput方法中(C#, WPF项目)

BUT it should be in the method PreviewTextInput (C#, WPF project)

因此正常的正则表达式不起作用

So the normal regex doesn't work

Regex regex = new Regex(@"^0|0.0|0\.[0-9]*|1\.0|1$");

我找到了一个正则表达式,它允许在PreviewTextInput方法中使用所有小数:

I've found a regex, which allows all decimals in the PreviewTextInput method:

Regex regex = new Regex("^[.][0-9]+$|^[0-1.]*[.,]{0,1}[0-9]*$");

如何将此正则表达式更改为仅接受0-1之间的小数?

How can a change this regex to only accept decimals between 0-1?

谢谢。

我的小数方法:

private void tb_PreviewTextInput(object sender, TextCompositionEventArgs e)
    {
        Regex regex = new Regex("^[.][0-9]+$|^[0-1.]*[.,]{0,1}[0-9]*$");
        e.Handled = !regex.IsMatch((sender as TextBox).Text.Insert((sender as TextBox).SelectionStart, e.Text));
    }

我的0-1之间的十进制方法(无效):

My method for decimals between 0-1 (doesn't work):

        private void tb_Surface_PreviewTextInput(object sender, TextCompositionEventArgs e)
    {
        Regex regex = new Regex(@"^(0?\.[0-9]+|1\.0)$");
        e.Handled = !regex.IsMatch(e.Text);
       // e.Handled = !regex.IsMatch((sender as TextBox).Text.Insert((sender as TextBox).SelectionStart, e.Text));

    }


推荐答案

@"^(0(?:\.\d+)?|1(?:\.0+)?)$"

0 1 也可以匹配,如果您不想匹配它们,并且点后必须有任何数字,则可以使用

0 and 1 also can be matched,if you don't want match them,and must have any digits after dot ,you can use

@"^(0\.\d+|1\.0+)$"

下面的代码是什么您需要,并且在文本框失去焦点时需要删除最后一个,例如 str.Trim('。')

The code below is what you want,and you need to remove the last dot when the textbox lost focus,such as str.Trim('.')

private void tb_Surface_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
    var patten = @"^(0(\.\d*)?|1(\.0*)?)$";
    Regex regex = new Regex(patten);
    e.Handled = !regex.IsMatch(e.Text);
    // e.Handled = !regex.IsMatch((sender as TextBox).Text.Insert((sender as TextBox).SelectionStart, e.Text));
}

这篇关于PreviewTextInput中的正则表达式:仅介于0.0到1.0之间的小数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆