简体   繁体   中英

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? ie 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.

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

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");

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?

try this :

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

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

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));

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM