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 MekaPosted Sep 19, 2011, 9:59 AM
^([1-9]\d{0,2}(,\d{3})+|[1-9]\d*|0)(\.\d+)?$
Dorababu MekaPosted Sep 19, 2011, 10:09 AM
VulpesPosted Sep 19, 2011, 10:05 AM
"0000,123.45"
However, Dorababu's expression seems to be dealing with all cases correctly, so I'd use that.
Gary KingPosted Sep 19, 2011, 9:57 AM
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
VulpesPosted Sep 19, 2011, 9:50 AM
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 KingPosted Sep 19, 2011, 9:48 AM
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)
Dorababu MekaPosted Sep 19, 2011, 9:43 AM