简体   繁体   English

创建正则表达式以接受空格/空格或十进制值

[英]create regex to accept blank/space or decimal value

我想在c#中创建正则表达式,对于具有空白/空格/ null的值或具有2个小数点的十进制值返回true。所以不接受除此之外的其他内容。

Although probably not the most efficient, this regular expression should do what you want: 虽然可能不是最有效的,但这个正则表达式应该做你想要的:

^((\d+[\.]\d{2})|([\.]\d{2})|()|\s*)$

It requires any decimal number to have two decimal places, but it does accept either 0.99 or .99 as an example. 它要求任何十进制数都有两个小数位,但它确实接受0.99或.99作为示例。

If you want to allow users to enter in 9 or 9.0 or 9.01 (that is, not force the user to enter in two decimal places) you can just modify the above like this: 如果你想允许用户输入9或9.0或9.01(也就是说,不强迫用户输入两位小数),你可以像这样修改上面的内容:

^((\d+([\.]\d{0,2})*)|([\.]\d{0,2})|()|\s*)$

It is just setting the quantifiers to {0,2} instead of {2}, and making the existence of decimals places optional. 它只是将量词设置为{0,2}而不是{2},并使小数位的存在可选。

^\s*(?:[+-]?\d*\.\d{2})?\s*$

匹配一个带有两个小数位的数字,可选地用空格包围,或者只用空/空白字符串。

使用这个正则表达式^(\\s+)|(([+-])?\\d+[,\\.]\\d{2})|()|(null)$

I would suggest this pattern to handle numbers and empty string scenario. 我会建议这种模式来处理数字和空字符串场景。

^[-+]?\d*(\.\d{2})?|\s*$

Reagrding NULL , I have experienced that when we pass null as an input in RegEx it throws ArgumentNullException . 重写NULL ,我经历过当我们在RegEx中传递null作为输入时它会抛出ArgumentNullException So my recommendation is to validate NULL using != operator by matching with null : 所以我的建议是使用!=运算符通过与null匹配来验证NULL

if(str != null && RegEx.IsMatch(str,@"^[-+]?\d*(\.\d{2})?|\s*$"))
   // valid data

where: 哪里:

str = string that contains data validating str =包含数据验证的字符串

Above pattern will also allow: -.00 or -0.00 as validate decimals. 上面的图案也将允许:-.00-0.00作为验证小数。

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

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