简体   繁体   English

RegEx为十进制,具有N位精度

[英]RegEx for decimal with N-digit precision

I would like to validate a decimal in the below range in my MVC3 application. 我想在我的MVC3应用程序中验证以下范围内的decimal

0.000000001 to 100.000000000 0.000000001至100.000000000

This is the Regex I tried but, it is not working: 这是我试过的正则Regex但它不起作用:

(^100([.]0{1,9})?)$|(^\\d{1,9}([.]\\d{1,9})?)$ (^ 100(0 {1,9})[。])$ |(^ \\ d {1,9}(\\ d {1,9})[。])$

  [RegularExpression(@"(^100([.]0{1,9})?)$|(^\d{1,9}([.]\d{1,9})?)$", 
   ErrorMessage ="Decimal value should be between 0.000000000 to 100.000000000")]
  [Range(0, 100, ErrorMessage = " % must be between {1} and {2}")]
  [Display(Name = "Percentage:")]
  public double? Percentage { get; set; }

Can anyone see what I am doing wrong? 谁能看到我做错了什么?

^(1\d\d|[1-9]\d|\d)\.\d{0,8}[1-9]$

In your second alternative you allow 1 to 9 digits before the dot. 在您的第二个替代方案中,您在点之前允许1到9位数字。

(^100([.]0{1,9})?)$|(^\d{1,9}([.]\d{1,9})?)$
                           ^

Change this to 将此更改为

^(100(\.0{1,9})?|\d{1,2}(\.\d{1,9})?)$

You can still "simplify" this, by moving the fraction out of the alternation 您仍然可以通过将分数移出更改来“简化”此操作

^(100|\d{1,2})(\.\d{1,9})?$

be aware that this expression does allow leading zeros like "00.1". 请注意,此表达式允许前导零如“00.1”。

See it here on Regexr 在Regexr上看到它

我相信这应该可以解决问题。

\d+\.\d{9}

This will be the required regex: 这将是必需的正则表达式:

(\d|[1-9]\d)(\.\d{1,9})?|100(\.0{1,9})?

In your regex, (^\\d{1,9}([.]\\d{1,9})?)$ matches one to nine digits (may be nine 0s upto nine 9s) followed by optional decimal part. 在你的正则表达式中, (^\\d{1,9}([.]\\d{1,9})?)$匹配一到九位数(可能是九个0到九个9),然后是可选的小数部分。 This is the problem. 这就是问题。

^(?:(?:[1]\d)|(?:[1-9]))?\d\.\d{9}$

This will match your range. 这将符合您的范围。 Also, it will not match the odd scenario of a double zero preceding the decimal like such: 00.000000000. 此外,它不会匹配小数点前的双零的奇数情况,如:00.000000000。 So, 00.000000000 will not be a valid number. 因此,00.000000000将不是有效数字。

If you want it with variable decimal places to the right of the 0, then you can use something like: 如果你想要它在0的右边有可变的小数位,那么你可以使用类似的东西:

^(?:(?:[1]\d)|(?:[1-9]))?\d\.\d{1,9}$

edit: sentence wording 编辑:句子措辞

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM