使用Regex检查字符串

时间:2014-01-02 16:39:08

标签: c# wpf regex string textbox

我的程序中有textBox,其中包含string,必须满足一些要求。我问这个问题是找出满足这些要求的最佳方法。

string不能为NullOrEmpty,且必须完全由整数组成。 string也可以包含空格,这是我的关键点,因为空格不是整数。

这就是我正在使用的(我知道目前可能有点多余):

//I test the string whenever the textBox loses focus
private void messageBox_LostFocus(object sender, RoutedEventArgs e)
{
      if (string.IsNullOrEmpty(TextBox.Text))
          ButtonEnabled = true;
      else if (Regex.IsMatch(TextBox.Text, @"^\d+$") == false)
      {
          //I think my problem is here, the second part of the if statement doesn't
          //really seem to work because it accepts characters if there is a space
          //in the string.
          if (TextBox.Text.Contains(" ") && !Regex.IsMatch(TextBox.Text, @"^\d+$"))
              ButtonEnabled = true;

          else
          {
              MessageBox.Show("Illegal character in list.", "Warning!", MessageBoxButton.OK, MessageBoxImage.Warning);
              ButtonEnabled = false;
          }
      }
      else 
          ButtonEnabled = true;
}

我从this answer获得了Regex解决方案。

问题:如何设置此textBox只接受以下值: “345 78”或“456”?

1 个答案:

答案 0 :(得分:5)

正则表达式似乎很简单。它可能是(具有指定约束)的行:

^([\s\d]+)?$

LostFocus处理程序中,您可以使用以下内容:

ButtonEnabled = Regex.IsMatch(TextBox.Text, @"^([\s\d]+)?$");

如果出现以下情况,将启用该按钮:

  1. 这是一个空字符串
  2. 仅包含数字和空格
  3. 如果您想要一个也会提取数字的正则表达式,您可以将模式更改为:

    ^(\s*(?<number>\d+)\s*)*$
    

    并使用number捕获组。

    请注意,第一个模式将匹配仅由空格组成的字符串。