简体   繁体   中英

Regex for decimal number validation in C#

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.

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.

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 != "";
}

If you are keen on using regex , the following will do:

^-?[0-9]*\.?[0-9]+$

See live demo

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