为什么我只能使用此正则表达式代码编写非数字字符

时间:2018-04-02 00:01:44

标签: c# regex

也许这真的是一个小错误,但我找不到它。

private void NumberValidationTextBox(object sender, TextCompositionEventArgs e)
{
    Regex regex = new Regex(@"^[-+]?[0-9]*[.,]?[0-9]+$");
    e.Handled = regex.IsMatch(e.Text);
}

我只能在输入中写入非数字字符,我不明白为什么?

更新

这里有更多信息:

我在xaml中制作了一个wpf程序:

<TextBox x:Name="textbox" PreviewTextInput="NumberValidationTextBox" HorizontalAlignment="Left" Height="8" Margin="133,74,0,0" Grid.Row="1" TextWrapping="Wrap" Text="" VerticalAlignment="Top" Width="112" Controls:TextBoxHelper.ClearTextButton="True"/>

所以在那之后我做了空虚

private void NumberValidationTextBox(object sender, TextCompositionEventArgs e)
{
    Regex regex = new Regex(@"^[-+]?[0-9]*[.,]?[0-9]+$");
    e.Handled = regex.IsMatch(e.Text);
}

更新2

找到另一个解决方案,但只有开头的减号无法正常工作,我尝试了不同的方法,但我不是正则表达式的专业人士,不知道如何解决。

        private void NumberValidationTextBox(object sender, TextCompositionEventArgs e)
    {
        Regex regex = new Regex("^[.][0-9]+$|^[0-9]*[.]{0,1}[0-9]*$");
        e.Handled = !regex.IsMatch((sender as TextBox).Text.Insert((sender as TextBox).SelectionStart, e.Text));
    }

更新3 新版本的正则表达式行:

^[-+]{0,1}[0-9]*[.,]{0,1}[0-9]{0,4}$

现在只出现问题,它可以用逗号或点开头,减号可以用逗号跟着

1 个答案:

答案 0 :(得分:2)

<强>更新

这看起来很可靠,你也可以使用正则表达式

private void NumberValidationTextBox(object sender, TextCompositionEventArgs e)
{

   if (!(sender is TextBox textBox))
   {
      return;
   }

   // use SelectionStart property to find the caret position
   // insert the previewed text into the existing text in the textbox
   var text = textBox.Text.Insert(textBox.SelectionStart, e.Text);

   if(text == "+" || text == "-")
      return;

   // if parsing is successful, set Handled to false
   e.Handled =  !double.TryParse(text, out var _) ;
}

原始答案

您当前已经编程,如果是一个数字然后处理事件,请停止处理。

你需要反转逻辑

private void NumberValidationTextBox(object sender, TextCompositionEventArgs e)
{
    Regex regex = new Regex(@"^[-+]?[0-9]*[.,]?[0-9]+$");
    // if its not matched then Handle the event
    // so it never gets to the display
    e.Handled = !regex.IsMatch(e.Text);
}

更新

我使用这种模式

^[-+]?[0-9]\d*(\.\d+)?$

<强>〔实施例

Regex regex = new Regex(@"^[-+]?[0-9]\d*(\.\d+)?$");
Console.WriteLine("Allowed  = " + regex.IsMatch("123"));
Console.WriteLine("Allowed  = " + regex.IsMatch("12.3"));
Console.WriteLine("Allowed  = " + regex.IsMatch(".123"));
Console.WriteLine("Allowed  = " + regex.IsMatch("+.123"));
Console.WriteLine("Allowed  = " + regex.IsMatch("00123"));
Console.WriteLine("Allowed  = " + regex.IsMatch("1.2.3"));
Console.WriteLine("Allowed  = " + regex.IsMatch("12..3"));
Console.WriteLine("Allowed  = " + regex.IsMatch("+123"));
Console.WriteLine("Allowed  = " + regex.IsMatch("+-1123"));

<强>输出

Allowed  = True
Allowed  = True
Allowed  = False
Allowed  = False
Allowed  = True
Allowed  = False
Allowed  = False
Allowed  = True
Allowed  = False

Demo Here