正则表达式掩码替换数字和只有一个连字符C#

时间:2017-08-25 11:42:04

标签: c# regex winforms

我看到了一个类似的主题(this)但无法达到理想的解决方案。

我需要什么:

适用于keypress的{​​{1}}事件的掩码,用TextBox替换非数字和过多的连字符。

允许:

enter image description here

我有什么困难?

检查同一表达式中只有一个连字符的输入。

我使用子字符串进入解决方案,它只在""中工作,但我想通过使用表达式和KeyUP事件来完成。

我已尝试过的内容:

keypress

预期:

enter image description here

如果您知道更好的方法,请告诉我们。 谢谢你的聆听。

4 个答案:

答案 0 :(得分:1)

您可以使用LINQ表达式仅获取数字和一个连字符:

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

答案 1 :(得分:0)

你好像迷路了:

表达式:(:? ) - 不是不匹配的组。正确的变体是:(?: )

digitsOnly - 它将是\d?

你不应该逃避-

如果您正在寻找-,请将其写下来。

对于正则表达式 - 更好地用文字写下,你在寻找什么。对于排除或接受,无所谓,但在英语中说,你需要什么。

请写下应该被接受的例子以及那些不应被接受的例子。

只获取数字,可能使用 - 之前,使用:

-?\d+

tests

答案 2 :(得分:0)

您可以将此用于非数字[^ \ d]:

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

1-23232

答案 3 :(得分:0)

我在这里搜索了一些替代品,使用Regex或MaskedTextBox(这对我没什么帮助,因为默认情况下我的textBox所在的toolStrip不支持。)

在一天结束时,我找到的最佳解决方案是处理每个字符的值输入:

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