I am now in need of a Reg Exp (for validation putsposes) that checks that the user enters a number according to the following rules.
- no alpha characters
- can have decimal
- can have commas for the thousands, but the commas must be correctly placed
Some examples of VALID values:
1.23
100
1,234
1234
1,234.56
0.56
1,234,567.89
INVALID values:
1.ab
1,2345.67
0,123.45
1.24,687
Thanks
Gary

Dorababu MekaRank #457 · 5.5K reputationPosted Sep 19, 2011, 5:59 AM EDT
^([1-9]\d{0,2}(,\d{3})+|[1-9]\d*|0)(\.\d+)?$
Dorababu MekaRank #457 · 5.5K reputationPosted Sep 19, 2011, 5:43 AM EDT
Gary King77 reputationPosted Sep 19, 2011, 5:48 AM EDT
Other examples of allowed numbers include:
1,234,567
1,234,567.89
12,345,678
12,345,678.9
123,456,789
and so on (basically any number that we as humans see as valid)
VulpesRank #55 · 29.2K reputationPosted Sep 19, 2011, 5:50 AM EDT
class Test
{
static void Main()
{
string[] numbers = new string[]
{
"1.23",
"100",
"1,234",
"1234",
"1,234.56",
"0.56",
"1,234,567.89",
"1.ab",
"1,2345.67",
"0,123.45",
"1.24,687",
"0.5"
};
string regExp = @"^(?!0{1,3},)\d{1,3}(,?\d{3})*(.\d{1,2})?$";
Regex r = new Regex(regExp);
foreach(string number in numbers)
{
Console.WriteLine(r.IsMatch(number));
}
Console.ReadKey();
}
}
Gary King77 reputationPosted Sep 19, 2011, 5:57 AM EDT
However, it is not perfect - for example 1234,567 (missing comma after the 1) is deemed valid by the Reg Exp.
Having said that, I think that the solution provided is "good enough"
Thanks
Gary
VulpesRank #55 · 29.2K reputationPosted Sep 19, 2011, 6:05 AM EDT
"0000,123.45"
However, Dorababu's expression seems to be dealing with all cases correctly, so I'd use that.
Dorababu MekaRank #457 · 5.5K reputationPosted Sep 19, 2011, 6:09 AM EDT