2

I'm using C# and .NET and I have a Regex that looks like this

"\D"

That matches all non-numeric characters however I don't want that to match a decimal point (.) and a negative sign (-). How can I do that with regular expressions?

So I tried Chris' and it made a few adjustments to make it work:

(I have a TextBox with a name of "Original")

 private void Original_TextChanged(object sender, EventArgs e) {
      Regex regex = new Regex(@"[^\d.-]", RegexOptions.IgnoreCase);
      Match match = regex.Match(Original.Text);
      if (match.Success) {
          Original.Text = regex.Replace(Original.Text, "");
          Original.SelectionStart = Original.TextLength;
      }
  }

This Original.SelectionStart = Original.TextLength; is because whenever it was replaced it put the selection to the beginning and that would seem a little weird to a user...

Mark Lalor
  • 7,820
  • 18
  • 67
  • 106

1 Answers1

5

You can use a negated character class to exclude numbers, ., and -. The expression for matching a single character like this is [^\d\.\-]. The caret indicates that the class is negated.

Regex.IsMatch("a f", @"^[^\d\.\-]+$"); // true
Regex.IsMatch("a_f", @"^[^\d\.\-]+$"); // true
Regex.IsMatch("a.f", @"^[^\d\.\-]+$"); // false
Regex.IsMatch("af-", @"^[^\d\.\-]+$"); // false
Regex.IsMatch("-42", @"^[^\d\.\-]+$"); // false
Regex.IsMatch("4.2", @"^[^\d\.\-]+$"); // false
Chris Schmich
  • 29,128
  • 5
  • 77
  • 94
  • 2
    There is actually no need to escape the `-` at that position: one can perfectly use `[^\d\.-]` as well. – mousio Apr 21 '11 at 22:51
  • 1
    @mousio: yes! Good point, though I'm always wary of doing that :) Silly superstition, I guess. – Chris Schmich Apr 21 '11 at 22:55
  • 2
    There’s no need to escape the dot either. Remember that bracketed character classes have a (nearly) completey different syntax from the rest of a regex. `[^\d.-]` would actually work. That said, it’s hard to blame people for escaping the HYPHEN-MINUS, since it and caret are position sensitive as to whether they need escaping to dispell their (ab)normal magic. – tchrist Apr 21 '11 at 22:59
  • 1
    Same goes for `.`, *anywhere* inside the (negated) character class, but I can agree with you to just escape anyway whenever you want to express the literal :] – mousio Apr 21 '11 at 23:00