0

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.

5
  • Your regex here is messed up. Is it a copy/paste error? Commented Aug 25, 2017 at 11:43
  • So, you are trying to capture a sequence: an optional : and a char other than a digit and -. It is wrong. Commented Aug 25, 2017 at 11:46
  • In my understanding this expression denies non-digit and hyphen. In conjunction with replace I remove everything that is not hyphen and digit. Commented Aug 25, 2017 at 11:49
  • 2
    Then it should be written as @"[^\d-]". It would not let you "control" the number of hyphens. What you may use is a regex like @"^\d*(?:-\d+)?$" and use it agains the whole text box text when it is already filled out, and let the user know if the test passed or not. Or perform any other action. Or, you may just check if the text already .Contains("-") and prevent that. Commented Aug 25, 2017 at 11:52
  • 1
    MaskedTextBox can save you some work Commented Aug 25, 2017 at 12:13

4 Answers 4

1

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());
Sign up to request clarification or add additional context in comments.

Comments

0

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

1 Comment

With @"[^\d-]" i trying to denie non-digit and hyphen. In conjunction with replace I remove everything that is not hyphen and digit
0

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("-", "");
      }
   }
}

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.