Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
482 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 Answer

0 votes
by (71.8m points)

You may try this regex.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...