【问题标题】:String checking with Regex使用正则表达式检查字符串
【发布时间】:2014-01-02 16:39:07
【问题描述】:

我的程序中有一个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 12 13 14”的字符串,是需要单独处理(1、12、13、14)还是读取为一个值1121314?
  • @Odrai 我将分别处理它们。
  • @gleng 我更新了我的问题,希望对您有所帮助。
  • 在这里regexpal.com 构建和测试你的正则表达式并尝试这个表达式...这应该让你开始:^[\d\W]*$

标签: c# wpf regex string textbox


【解决方案1】:

正则表达式看起来很简单。它可能类似于(具有指定的约束):

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

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

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

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

  1. 这是一个空字符串
  2. 它只包含数字和空格

如果您想要一个也能提取数字的正则表达式,您可以将模式更改为:

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

并使用number 捕获组。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-26
    • 1970-01-01
    相关资源
    最近更新 更多