Eric after dark
Eric after dark

Reputation: 1808

String checking with Regex

I have a textBox in my program that contains a string that has to meet a few requirements. I'm asking this question to figure out the best way to meet these requirements.

This string can't be NullOrEmpty and it must be completely composed of integers. The string can also contain spaces, which is my sticking point because spaces aren't integers.

This is what I'm working with (I'm aware that it may be a bit redundant at the moment):

//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;
}

I got the Regex solution from this answer.

Question: How do I make it so that this textBox only accepts values like these: "345 78" or "456"?

Upvotes: 0

Views: 359

Answers (1)

Simon Belanger
Simon Belanger

Reputation: 14870

The regular expression seems simple enough. It could be something along the line of (with the specified constraints):

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

In your LostFocus handler, you could use something like this:

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

The button will be enabled if:

  1. It's an empty string
  2. It contains only digits and spaces

If you want a regular expression that will extract the numbers as well, you could change the pattern to:

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

And use the number capture group.

Note that the first pattern will match strings that are composed of spaces only.

Upvotes: 5

Related Questions