开发者

Regex for numeric characters and .&-

I'm using C# and 开发者_JAVA百科.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...


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜