views:

220

answers:

2

Hi,

I'm trying to come up with a regex to validate a double value. I will admit that I am crap at regex and really should buy a book... Anyway the range is large so here goes:

.01 to 99.99, is the range, with the leading '00' being optional, as is the '.' and the same for the trailing '.00'. So the user could type in 0.1 00.01, 0.11, 1, 1.0 1.00 and these all would be valid.

Thanks, r.

+5  A: 

Rather than a RegEx, why not use double's TryParse method?

string[] sa = new string[] { "00.01", "1.00", "xx" };
double d;
bool isValid;
foreach (string s in sa)
{
    isValid = double.TryParse(s, out d) && d >= 0.01d && d <= 99.99d;
    Console.WriteLine("{0}: {1}", s, isValid.ToString());
}
RedFilter
Michael Petrotta
It even works with non-US cultures! +1
dtb
+1 for suggesting not to use regular expressions, although your answer is incomplete - you should edit it to add a range check.
Mark Byers
Thanks for suggesting tryparse() for some reason I have been using reg expressions and got stuck in the mindset... tryparse was just so much easier to implement... lol thanks.
flavour404
Added range check, missed that part.
RedFilter
A: 
^[0-9]{0,2}\.?[0-9]{0,2}$

you can try it out here: http://www.regular-expressions.info/javascriptexample.html

kartheek
Doesn't work for all the examples.
Mark Byers
This actually also accepts 3 or 4 digit whole numbers (100-999 and 1000-9999) as well as the empty string and the string `.`
eldarerathis
@Mark Byers, it does work for the all the examples quoted: 0.1 00.01, 0.11, 1, 1.0 1.00. And, thanks for pointing out @eldarerathis - it matches 3/4 digit whole numbers and empty string as well :-/
kartheek