1

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.

G Gr
  • 6,030
  • 20
  • 91
  • 184

5 Answers5

7

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");
M.Babcock
  • 18,753
  • 6
  • 54
  • 84
  • Badcock this throws an exception I got confused earlyier I need to handle the error, soon the user hits return an error is displayed in the console saying they have entered a wrong character only numbers allowed. Sorry Im quite tired and its been a heavy day. – G Gr Mar 07 '12 at 20:55
  • Yeah this method doesnt work for some reason? If I encapsulate it just in the first insert I get an invalid input straight away if it put it at the bottom and hit a letter and return i still get an exception? – G Gr Mar 07 '12 at 21:09
  • 1
    A guess: Potentially `CultureInfo` would be valuable to pass as well, and maybe just debugging it and seeing what value is being passed in would help. In the end your question here has been answered. – M.Babcock Mar 07 '12 at 21:12
3

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?

Oded
  • 489,969
  • 99
  • 883
  • 1,009
  • decimal.TryParse is an alternative for verifying that it can be parsed without needing to use exceptions. – Servy Mar 07 '12 at 20:35
  • @Servy - True, but it is not clear to me from the question whether exceptions are wanted or not. – Oded Mar 07 '12 at 20:36
  • TryParse is better. See: http://stackoverflow.com/questions/467613/parse-v-tryparse – Matt Burland Mar 07 '12 at 20:37
  • 1
    @MattBurland - No, it is _different_. It _depends_ on the wanted behaviour. If you want an exception, `TryParse` is **not** better. – Oded Mar 07 '12 at 20:38
  • 2
    @Oded Which is why I mentioned an alternative, rather than a correction. Let the OP decide which is appropriate. – Servy Mar 07 '12 at 20:38
  • I do want it thrown with an exception sorry I re-edited my post. Thank you tho for the comments. – G Gr Mar 07 '12 at 20:46
  • @Garrith - Then you do need to use `Parse` and not `TryParse`. But you didn't explain what is not working for you, as your code looks like it _would_ throw exception if the wrong input is entered. – Oded Mar 07 '12 at 20:47
  • @Garrith - So you _do_ want exceptions, or you _don't_ want exceptions? – M.Babcock Mar 07 '12 at 20:55
  • @M.Babcock - He got you too! I believe he doesn't want exceptions, in which case, `TryParse` is the right option. – Oded Mar 07 '12 at 20:56
  • I dont want it thrown with exceptions i need the error handled but with minimal effort I just dont have a clue how to. – G Gr Mar 07 '12 at 20:56
  • If I use TryParse alone I get an overload method thing i also dont know how to add a method into the case/break. – G Gr Mar 07 '12 at 20:58
  • 1
    @Garrith - M.Babcock added an example in his [answer](http://stackoverflow.com/a/9608645/1583). – Oded Mar 07 '12 at 20:59
  • Yeah I seen thanks Oded for the help bud! Think al call it a night after this... sigh – G Gr Mar 07 '12 at 21:01
2

try this :

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

   Regex regex = new Regex ("^\d+(\.\d{1,2})?$");
    MatchCollection matches = regex.Matches(text);
     if (matches.Count>0)......
Royi Namir
  • 144,742
  • 138
  • 468
  • 792
2

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));
driis
  • 161,458
  • 45
  • 265
  • 341
  • thats abit hefty wouldnt i have to do this for each insertion? – G Gr Mar 07 '12 at 20:40
  • 2
    If you're going to throw an exception anyway then why bother with the `TryParse`? – M.Babcock Mar 07 '12 at 20:45
  • 1
    @Garrith That's what methods are for, so that you don't need to repeat the same code over and over again. Make a method `GetDoubleFromUser()` that returns a double and contains code more or less like this (but with a return). – Servy Mar 07 '12 at 20:45
1

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;
Matt Burland
  • 44,552
  • 18
  • 99
  • 171
  • myArrai1[0] = double.TryParse(Console.ReadLine()); gives no overload method for try parse? – G Gr Mar 07 '12 at 20:37
  • @Garrith You can google double.TryParse to see the signature for the method and examples of its use. – Servy Mar 07 '12 at 20:40
  • Read the MSDN documentation. You need to pass a double as an out parameter. driis' answer is almost correct. – Matt Burland Mar 07 '12 at 20:40