我正在尝试编写一个正则表达式来匹配表示为 .25
的十进制倍数的数值(例如 1.25
、14.75
).
// Must Match
1.0
1.25
1.250000
1.5
1.500
1.75
1.7500
// Must Not Match
1.2
1.46
1.501
1.99
到目前为止,我有以下表达式:\d+(\.((0+)|(250*)|(50*)|(750*)))
。当我使用像 gskinner.com/regexr 这样的在线工具时它会起作用。 。当我在验证属性中使用表达式来为 EntityFramework 数据库提供种子时,它会产生验证错误:
[RegularExpression(@"^\d+(\.((0+)|(250*)|(50*)|(750*)))$", ErrorMessage = "Hours must be 15 minute increments expressed as decimals (ex. .0, .25, .5, .75)")]
public double Hours { get; set; }
类似的问题( I am looking for a way to round the decimal portion of numbers up or down to the nearest .25, .5, .75, or whole number ),但我需要使用正则表达式来使用上述数据注释。
问题:
有人看出我的表情有什么问题吗?
如果您可以扩展它以支持整数(例如
4
或4.25
但不是4。
或4.62
)
最佳答案
要匹配此类数字,请使用正则表达式模式
(?!0\d)\d+(?:[.](?:25|5|75|0)0*)?(?!\d)
要验证输入是这样的数字,请使用正则表达式模式
^(?!0\d)\d+(?:[.](?:25|5|75|0)0*)?$
在这两种情况下,第一部分 (?!0\d)
是可选的,以禁止匹配/验证具有无效前导零的数字,例如 000003.250
,当match 会修剪它们并只需要 3.250
;如果正则表达式中存在此可选部分,验证将失败。
关于c# - 正则表达式模型验证 : Whole Number or Decimal Multiples of . 25,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13390037/