Search code examples
c#regexwpffloating-pointformatter

Regex floating point Number Formatter for Wpf Textbox


I saw Regex today for the first time. I need a regex formatter for my WPF Textbox like this: 12345,1234 I need a decimal separator like "," or "." and negative Numbers should be allowed. So you can write something like this:

230,56 / 1289,4 / -1.9 / 63478,1252 / 0.3265

This should not be possible:

086,344 / 34,7000 / 1.0×10−4

A 0 at first if there is not a comma behind there should not be allowed. And if the last Number after the Comma is a 0 is also bad. No scientific notation.

I found a code for simple integer values:

private void Int_PreviewTextInput(object sender, System.Windows.Input.TextCompositionEventArgs e)
        {
            // Just Ints
            Regex regex = new Regex("[^0-9]+");
            e.Handled = regex.IsMatch(e.Text);
        } 

So how does a formatter for floating point numbers like my description looks like?


Solution

  • Looking at your requirements, it seems that the following pattern would work:

    ^-?(?!.*0$)(?!0\d)\d+(?:[,.]\d+)?$
    

    See the demo


    • ^ - Start string ancor.
    • -? - Optional hyphen to allow for negative values.
    • (?!.*0) - Negative lookahead to prevent a string that ends with 0.
    • (?!0\d) - Negative lookahead to prevent a string that starts with 0 and a digit.
    • \d+ - Any digit at least once.
    • (?: - Open non-capture group.
      • [,.] - A comma or dot as decimal delimiter.
      • \d+ - One or more digits.
      • )? - Close non-capture group and make it optional.
    • $ - End string ancor.