Reputation: 1891
I need regular expression which allows positive as well as negative range decimals values
like .89
, -1000
, 0.00
, 0
, 300
, .....
My regex is ^\d*\.?\d*
Problem is that when you entered special characters like $
, !
, *
then it accepts those characters.
Upvotes: 0
Views: 9185
Reputation: 587
You missed a backslash! A single dot has a different meaning in Regex expressions.
public static bool IsValidDecimal()
{
string input = "132456789"
Match m = Regex.Match(input, @"^-?\d*\.?\d+");
return m.Success && m.Value != "";
}
Upvotes: 1
Reputation: 9619
If you are keen on using regex
, the following will do:
^-?[0-9]*\.?[0-9]+$
Upvotes: 2
Reputation: 98740
Instead of regex, I would parse it with decimal.Parse
with AllowDecimalPoint
and AllowLeadingSign
styles and a culture that has .
as a NumberDecimalSeparator
like InvariantCulture
.
var d = decimal.Parse("-.89",
NumberStyles.AllowDecimalPoint | NumberStyles.AllowLeadingSign,
CultureInfo.InvariantCulture);
This captures all needs you mentioned.
Upvotes: 1