[英]Regex for decimal number validation in C#
我需要允許正負范圍小數的正則表達式
像.89
, -1000
, 0.00
, 0
, 300
,......
我的正則表達式是^\\d*\\.?\\d*
問題是,當您輸入$
,!之類的特殊字符時!
, *
然后接受這些字符。
代替正則表達式,我將使用decimal.Parse
進行解析,並使用AllowDecimalPoint
和AllowLeadingSign
樣式以及具有的區域性.
如NumberDecimalSeparator
一樣,如InvariantCulture
。
var d = decimal.Parse("-.89",
NumberStyles.AllowDecimalPoint | NumberStyles.AllowLeadingSign,
CultureInfo.InvariantCulture);
這捕獲了您提到的所有需求。
您錯過了反斜線! 在正則表達式中,單個點具有不同的含義。
public static bool IsValidDecimal()
{
string input = "132456789"
Match m = Regex.Match(input, @"^-?\d*\.?\d+");
return m.Success && m.Value != "";
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.