Caique Romero
Caique Romero

Reputation: 633

Regex mask with replace for digits and only one hyphen C#

I saw a similar topic (this) but could not reach the ideal solution.

What I need:

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

Allowing:

enter image description here

What is my difficulty?

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

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

What I've already tried:

  using System.Text.RegularExpressions;

    //trying to denie non-digit and hyphen. 
    //In conjunction with replace I remove everything that is not hyphen and digit
    private static Regex MyMask = new Regex(@"[^\d-]");


    private void inputSequential_KeyUp (object sender, KeyEventArgs e)
    {
       if (! String.IsNullOrEmpty (inputSequential.Text)
       {
          inputSequential.Text = MyMask.Replace (inputSequential.Text, "");

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

Expected:

enter image description here

If you know better ways to do this please let me know. Thanks for listening.

Upvotes: 0

Views: 1144

Answers (4)

LetzerWille
LetzerWille

Reputation: 5658

You can use this for nondigit [^\d]:

var st = "1kljkj--2323'sdfkjasdf2";
var result = Regex.Replace(st, @"^(\d).*?(-)[^\d]*(\d+)[^\d]*", @"$1$2$3");

1-23232

Upvotes: 0

Caique Romero
Caique Romero

Reputation: 633

I searched here for some alternatives, with Regex or MaskedTextBox (This did not help me much because by default it is not supported in toolStrip where my textBox was).

At the end of the day the best solution I found was dealing with the input of values ​​to each char:

private void inputSequencial_KeyPress(object sender, KeyPressEventArgs e)
{
   //Allow only digits(char 48 à 57), hyphen(char 45), backspace(char 8) and 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;
         //If the first char is a hyphen or 
         //a hyphen already exists I reject the entry
         if (inputSequencial.Text.Length == 0 || count > 0)
         {
            e.Handled = true;
         }
         break;
      }
   }
   else
   {
      e.Handled = true; //Reject other entries
   }
}

private void inputSequencial_KeyUp(object sender, KeyEventArgs e)
{
   //if last char is a hyphen i replace it.
   if (inputSequencial.Text.Length > 1)
   {
      string lastChar = inputSequencial.Text.Substring(inputSequencial.Text.Length - 1, 1);
      if (lastChar == "-")
      {
         inputSequencial.Text.Replace("-", "");
      }
   }
}

Upvotes: 0

KBO
KBO

Reputation: 675

You can use a LINQ expression to get only the numbers and one hyphen:

string input = "12-3-47--Unwanted Text";
int    hyphenCount = 0;
string output = new string(input.Where(ch => Char.IsNumber(ch) || (ch == '-' && hyphenCount++ < 1)).ToArray());

Upvotes: 1

Gangnus
Gangnus

Reputation: 24464

You seem at lost:

that expression: (:? ) - is not a nonmatched group. The correct variant is : (?: )

digitsOnly - it will be \d?

You should not escape -

If you are looking for a -, simply write it down.

For regex - Better write down in words, what are you looking for. For excluding or for taking in, does not matter, but SAY IN ENGLISH, what do you need.

Please, write down examples that should be accepted and these ones that should NOT be accepted.

For getting only numbers, possibly with - before, use:

-?\d+

tests

Upvotes: 0

Related Questions