G Gr
G Gr

Reputation: 6090

Regex C# console app

How do I add a regular expression which will accept decimal places (5.23) but nothing else in a break like so? i.e handle only numbers and decimal places which will throw an error if anything other than this is typed or returned:

    case 1:
    double[] myArrai1 = new double[3];
    Console.WriteLine("Insert a number");
    myArrai1[0] = double.TryParse(Console.ReadLine()); // no overload method?
     Console.WriteLine("Insert a number");
     myArrai1[1] = double.Parse(Console.ReadLine());
    Console.WriteLine("Insert a number");
    myArrai1[2] = double.Parse(Console.ReadLine());
    break;

Cheers guys.

P.s not sure on how to programme it in with the break also has to be without exception.

Upvotes: 1

Views: 2322

Answers (5)

M.Babcock
M.Babcock

Reputation: 18965

Regex is a little heavy for validating a double. Use double.TryParse instead (it'll return false if the input is invalid).

double dbl;
if (!double.TryParse(Console.ReadLine(), out dbl))
    Console.WriteLine("Invalid input");

Upvotes: 7

Matt Burland
Matt Burland

Reputation: 45155

Did you want to just validate what the user inputs, or stop them from putting in invalid characters in the first place?

In the first case, regex aren't really needed. You are on the right track with double.Parse, but what you want to do is double.TryParse. First read the user input into a string, then TryParse it into a double. If TryParse returns false, tell you user their input is invalid and prompt them to enter it again.

FWIW: here's how I'd do it (warning: untested code), which may or may not be what you need:

case 1:
double[] myArrai1 = new double[3];
for (int i=0; i < myArrai1.length; i++) {
    Console.WriteLine("Insert a number");
    while (!double.TryParse(Console.Readline(), out myArrai1[i])) {
        Console.WriteLine("Invalid entry. Please enter a number.");
    }
}
break;

Upvotes: 1

driis
driis

Reputation: 164341

You will probably be better off just using .NET's double parsing instead of trying to re-invent it in Regex. You can use Double.TryParse to test the string and do the conversion if the number can be parsed:

 Console.WriteLine("Insert a number");
 string input = Console.ReadLine();
 double value;
 if (!Double.TryParse(input, NumberStyles.Any, CultureInfo.InvariantCulture, out value)) 
    throw new InvalidOperationException(String.Format("{0} could not be parsed as a valid number.", input));

Upvotes: 2

Royi Namir
Royi Namir

Reputation: 148694

try this :

/^\d+(\.\d{1,2})?$/;

   Regex regex = new Regex ("^\d+(\.\d{1,2})?$");
    MatchCollection matches = regex.Matches(text);
     if (matches.Count>0)......

Upvotes: 2

Oded
Oded

Reputation: 499252

You don't need a Regex for this.

You can simply use decimal.Parse or double.Parse - if the input string is in the wrong format, you will get a FormatException.

The code you posted appears to be right - what's not working?

Upvotes: 3

Related Questions