Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
486 views
in Technique[技术] by (71.8m points)

c# - Regex in PreviewTextInput: only decimals between 0.0 and 1.0

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

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$");

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]*$");

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

Thanks.

My method for decimals:

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));
    }

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));

    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You may try this regex.

@"^(?:0?.[0-9]+|1.0)$"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...