且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将正则表达式与数值和小数匹配

更新时间:2021-07-16 21:44:42

您需要处理两种可能性(没有小数部分的数字和没有整数部分的数字):

You need to handle the two possibilities (numbers without a decimal part and numbers without an integer part):

/\A-?(?:\d+(?:\.\d*)?|\.\d+)\z/
#^   ^  ^            ^^     ^---- end of the string
#|   |  |            |'---- without integer part
#|   |  |            '---- OR
#|   |  '---- with an optional decimal part
#|   '---- non-capturing group
#'---- start of the string

或将所有选项都设为可选并确保至少有一位数字:

or make all optional and ensure there's at least one digit:

/\A-?+(?=.??\d)\d*\.?\d*\z/
#  ^  ^  ^        ^---- optional dot
#  |  |  '---- optional char (non-greedy)
#  |  '---- lookahead assertion: means "this position is followed by"
#  '---- optional "-" (possessive)

注意:我使用非贪婪量词 ?? 只是因为我相信整数部分的数字更频繁,但这可能是一个错误的假设.在这种情况下,将其更改为贪婪量词 ?.(无论您对未知字符"使用哪种量词都没有关系,这不会改变结果.)

Note: I used the non-greedy quantifier ?? only because I believe that numbers with integer part are more frequent, but it can be a false assumption. In this case change it to a greedy quantifier ?. (whatever the kind of quantifier you use for the "unknow char" it doesn't matter, this will not change the result.)