0

Im working on an assignment for class and it includes using some checks for input to ensure valid input is given, using a regex expression. The example given for the IsValidNumber check is string regex = @"^-?\\d*(\\.\\d+)?$";

I'm not really sure if this is actually checking for valid numbers because i've never seen that before. Wouldn't something like string regex = @"^[0-9]\d*$ work or am i missing something? Note I do need to be able to pass through a float and not just an int.

UPDATE: Using the regex I was provided, i ran the program only to run into an issue with the error check that didn't allow anything to pass through even if valid

Here is the method that is calling IsNumberValid

private static string GetNumericInput(string c)
    {
        do
        {
            Console.Write(c);
            string var = Console.ReadLine();
            if (!String.IsNullOrEmpty(var) && IsValidNumber(var))
            {
                return var;
            }
            else
            {
                Console.WriteLine("Input was either Null/Empty, or contained non-numeric characters.");
                Console.WriteLine("Retry input.");
                Console.WriteLine();
            }
        }
        while (true);
    }

and here is IsValidNumber

public static bool IsValidNumber(string value)
        {
            string regex = @"^-?\\d*(\\.\\d+)?$";

            return Regex.IsMatch(value, regex);
        }

I'm not entirely sure how to read breakpoints for errors but when i put breakpoints at string regex = @"^-?\\d*(\\.\\d+)?$"; and return Regex.IsMatch(value, regex); it shows value for regex as null and "^-?\\d*(\\.\\d+)?$" respectively.

Nick B
  • 33
  • 6

2 Answers2

4

The regex is taking into consideration the decimal point, i.e. it matches not just integers but also floating point numbers. This is what the \\. catches. Also the ^-? matches a possible negative sign. ^[0-9]\d* only matches positive integers.

The statement string regex = @"^-?\\d*(\\.\\d+)?$"; creates a regex pattern that's literally ^-?\\d*(\\.\\d+)?$ because of the @ at the front of the string. You don't need to use double backslashes in this case, simply:

string regex = @"^-?\d*(\.\d+)?$";
M A
  • 69,673
  • 13
  • 131
  • 165
2

In addition to @manouti answer of this regex takes in consideration floating point numbers as well, it also takes in account for negative numbers

austin wernli
  • 1,803
  • 10
  • 15