Boris G

Boris G

  • 1.8k
  • 63
  • 1k

Help with regular expression for negative real numbers.

Aug 14 2019 10:02 AM
I would like to make a regular expression that limits the textboxes I have to negative real numbers. Unfortunately, the best I have been able to do is to limit the text box to numbers only. I have tried several "working" examples from around the web, but none of them worked for me. Here is my code based on my book and how I would think I should build the regular expression.
 
  1. using System.Text.RegularExpressions;  
  2. using System.Windows;  
  3. using System.Windows.Input;  
  4.   
  5. namespace WPF_Test_Unit  
  6. {  
  7.     /// <summary>  
  8.     /// Interaction logic for MainWindow.xaml  
  9.     /// </summary>  
  10.     public partial class MainWindow : Window  
  11.     {  
  12.         public MainWindow()  
  13.         {  
  14.             InitializeComponent();  
  15.             this.SizeToContent = SizeToContent.WidthAndHeight;  
  16.         }  
  17.   
  18.         private void CheckForNumber(object sender, TextCompositionEventArgs e)  
  19.         {  
  20.             Regex regex = new Regex(@"\-?\d+\.?\d+");  
  21.             e.Handled = !regex.IsMatch(e.Text);  
  22.         }  
  23.     }  
  24.   
  25. }  
 
My idea is that I would need 0 or 1 negative sign "-", then one or more digits, an optional decimal "." and then one or more digits trailing the decimal point.
 
Below is the XAML that uses the function.
 
  1. <TextBox Grid.Row="3" Grid.Column="1" VerticalAlignment="Center" PreviewTextInput="CheckForNumber" HorizontalAlignment="Center" FontSize="20" Width="170" Height="40" />  
I have tried many combinations of regular expressions, but the only results I can get with preventing characters in the textbox a numbers-only situation. Trying to remove (or allow) other characters seems not to work.

Answers (9)