Mask with Regex and replace to allow only digits and a single hyphen

2

What I need:

A mask that works on the keypress event of a TextBox replacing non-numeric and excessive hyphens with "" .

What is my difficulty:

Check for the entry of only one hyphen in the same expression.

I got into the solution using substring and only worked on KeyUP , but I wanted to get through an expression.

What I've already tried:

using System.Text.RegularExpressions;

private static Regex digitsOnly = new Regex(@"(:?[^\d\-])");


private void inputSequencial_KeyUp(object sender, KeyEventArgs e)
{
   if (!String.IsNullOrEmpty(inputSequencial.Text)
   {
      inputSequencial.Text = digitsOnly.Replace(inputSequencial.Text, "");

      //MatchCollection matches = Regex.Matches(inputSequencial.Text, "[\-]");
      //
      //if (matches.Count > 1)
      //{
      //    for (int i = 1; i <= matches.Count - 1; i++)
      //    {
      //         inputSequencial.Text = inputSequencial.Text.Substring(0, matches[i].Index-1) + inputSequencial.Text.Substring(matches[i].Index, inputSequencial.Text.Length);
      //         inputSequencial.Text = inputSequencial.Text.Replace(inputSequencial.Text[matches[i].Index].ToString(), "");
      //    }
      //}
   }
}

Expected result:

If you know better ways to do this please let me know. Thank you for your attention.

    
asked by anonymous 25.08.2017 / 13:42

1 answer

1

I've tried some alternatives here, with Regex or MaskedTextBox (This did not help me much because by default it is not accepted in the local toolStrip where my textBox was).

At the end of the day, the best solution I found was to treat the input values for each character as follows:

private void inputSequencial_KeyPress(object sender, KeyPressEventArgs e)
{
   //So permite a entrada de digitos(char 48 à 57), hífen (char 45), backspace(char 8) e delete(char 127)
   if ((e.KeyChar >= 48 && e.KeyChar <= 57) || e.KeyChar == 45 || e.KeyChar == 8 || e.KeyChar == 127)
   {    
      switch (e.KeyChar)
      {
         case (char)45:
         int count = inputSequencial.Text.Split('-').Length - 1;
         //Se for o primeiro caracter digitado no input ou 
         //se já existir um hífen evito a inserção.
         if (inputSequencial.Text.Length == 0 || count > 0)
         {
            e.Handled = true;
         }
         break;
      }
   }
   else
   {
      e.Handled = true; //Desprezo outras entradas
   }
}

private void inputSequencial_KeyUp(object sender, KeyEventArgs e)
{
   //Se o ultimo caracter for um hífen eu removo ele.
   if (inputSequencial.Text.Length > 1)
   {
      string lastChar = inputSequencial.Text.Substring(inputSequencial.Text.Length - 1, 1);
      if (lastChar == "-")
      {
         inputSequencial.Text.Replace("-", "");
      }
   }
}
    
25.08.2017 / 16:35