• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 318
  • Last Modified:

Regex for numeric check

The below only works if the number isn't negative or have decimals.  How would I modify it to handle such?

if (Regex.IsMatch(MyString, @"^\d+$"))
  Console.WriteLine(MyString + " is numeric");
1 Solution
Jai STech ArchCommented:
if (Regex.IsMatch(MyString, @"^-?(\d+)(\.\d*)?$"))
      Assuming that you don't care about IEEE notations like "NaN" or "Infin-
       ity", you probably just want to use a regular expression.

          if (/\D/)            { print "has nondigits\n" }
          if (/^\d+$/)         { print "is a whole number\n" }
          if (/^-?\d+$/)       { print "is an integer\n" }
          if (/^[+-]?\d+$/)    { print "is a +/- integer\n" }
          if (/^-?\d+\.?\d*$/) { print "is a real number\n" }
          if (/^-?(?:\d+(?:\.\d*)?|\.\d+)$/) { print "is a decimal number\n" }
          if (/^([+-]?)(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?$/)
                               { print "a C float\n" }

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now