我需要将正则表达式与带小数的数字值匹配。目前我有/^-?[0-9]\d*(.\d+)/但它不占 .00 我该如何解决这个问题
当前有效:
1
1.0
1.33
.00
当前无效:
Alpha Character
最佳答案
您需要处理两种可能性(没有小数部分的数字和没有整数部分的数字):
/\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
或者全部设为可选并确保至少有一位数字:
/\A-?+(?=.??\d)\d*\.?\d*\z/
# ^ ^ ^ ^---- optional dot
# | | '---- optional char (non-greedy)
# | '---- lookahead assertion: means "this position is followed by"
# '---- optional "-" (possessive)
注意:我使用非贪婪量词 ??
只是因为我相信带有整数部分的数字更频繁,但这可能是一个错误的假设。在这种情况下,将其更改为贪婪量词 ?
。 (无论您对“未知字符”使用何种量词都没有关系,这不会改变结果。)
关于ruby - 将正则表达式与数值和小数匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36946443/