我想要一个正则表达式,它只允许在文本框中输入介于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之间的小数
发布评论