PreviewTextInput中的正则表达式:仅介于0.0到1.0之间的小数

编程入门 行业动态 更新时间:2024-10-28 06:29:06
本文介绍了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之间的小数

本文发布于:2023-11-10 23:03:56,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1576708.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:小数   正则表达式   PreviewTextInput

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!