Regex允许数字大于0.5

Regex to allow number greater than 0.5

本文关键字:大于 数字 许数字 Regex      更新时间:2023-09-26

嗨,我现在正在处理一些正则表达式,我想添加条件以只允许大于0.5的数字,这是我的正则表达式

^(?![.0]*$)[0-9]+(?:'.[1-9]{1,2})?$

我只想0和0.5之间的值与此不匹配。感谢

正则表达式非常棒,但它们可能很难阅读和维护。这感觉就像是一个场景,您只需要解析字符串并比较值。

var num = parseFloat(input);
if (num > 0.5)
    ...
(^(?![.0]*$)[1-9]+(?:'.[0-9]{1,2})?$)|(^(?![.0]*$)[0]+(?:'.[5-9][0-9]*)?$)

它也很容易阅读!

此正则表达式允许两位小数和大于0.50 的数字

^((?!0*('.0+)?$)[0-9]+|[0-9]+[0-9]'.[0-9]{1,2}+|[1-9]'.[0-9]+|0'.[5-9][0-9]?)$

您真的应该使用@dontangg的答案。

但如果你想要一个正则表达式,这里有一个可以完成任务:

^(?:0'.5[1-9]'d*|0'.[6-9]'d*|'d+[1-9](?:'.'d+)?)$

解释:

^                   : begining of string
    (?:             : begining of non-capture group
        0'.5[1-9]'d*:  0. followed by number greater than 50
        |           :
        0'.[6-9]'d* : 0. followed by number greater than 5 then any number of digits
        |           : OR
        'd+[1-9]    : any digit followed by number from 1 to 9
        (?:         : begining of non-capture group
            '.'d+   : a dot followed by any digits
        )?          : end of non capture group, optional
    )               : end of non-capture group
$                   : end of string

它匹配:

0.51
12
12.34

不匹配:

0
0.2
0.25
0.5
0.50

此regexp可能工作:(请检查此处)

^([0-9]+|[0-9]+[0-9]'.[0-9]+|[1-9]'.[0-9]+|0'.[5-9][0-9]*)$