将正则表达式与数值和小数匹配 [英] Match regex with numeric value and decimal

查看:35
本文介绍了将正则表达式与数值和小数匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将正则表达式与带小数的数字值匹配.目前我有/^-?[0-9]\d*(.\d+)/但它不占 .00我该如何解决这个问题

I need to match regex to value that is numeric with decimal. Currently I have /^-?[0-9]\d*(.\d+)/ but it does not account for .00 How would I fix that

当前有效:

1
1.0 
1.33
.00

当前无效:

Alpha Character 

推荐答案

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

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.)

这篇关于将正则表达式与数值和小数匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆