[英]Regular expression for text input
I want users to be allowed to enter numbers, up to 3 digits before the decimal place, with an optional decimal place and a maximum of 2 digits after the optional decimal place. 我希望允许用户输入数字,小数位前最多3位,可选的小数位,可选小数位后最多2位。
I want it to match: 12, 123, 123.5, 123.55, 123. I do not want it to match: abc, 1234, 123.555 我希望它匹配:12、123、123.5、123.55、123。我不希望它匹配:abc,1234、123.555
What I have so far it: ^\\d{0,3}(.?)\\d{0,2}$ 到目前为止,我所拥有的是:^ \\ d {0,3}(。?)\\ d {0,2} $
At the moment it is still matching 1234. I think I need to use the look behind operator somehow but I'm not sure how. 目前,它仍与1234相匹配。我想我需要以某种方式使用“后面看”运算符,但不确定如何。
Thanks 谢谢
Try this: 尝试这个:
^\d{0,3}(?:\.\d{0,2})?$
Or better, to avoid just a .
或更好,以避免只是一个
.
: :
^(?:\d{1,3}(?:\.\d{0,2})?|\.\d{1,2})$
Specifically, note: 具体来说,请注意:
^\\d{0,3}(\\.?)\\d{0,2}$
isn't correct. ^\\d{0,3}(\\.?)\\d{0,2}$
也不正确。 With the dot optional, it can match 12378
: \\d{0,3}
matches 123
, (\\.?)
doesn't match anything, and \\d{0,2}
matches 78
. 12378
: \\d{0,3}
匹配123
, (\\.?)
不匹配任何内容, \\d{0,2}
匹配78
。 Working example: http://rubular.com/r/OOw6Ucgdgq 工作示例: http : //rubular.com/r/OOw6Ucgdgq
Maybe this (untested) 也许这(未经测试)
^(?=.*\\d)\\d{0,3}\\.?(?<=\\.)\\d{0,2}$
Edit - the above is wrong. 编辑 -上面是错误的。
@Kobi's answer is correct. @Kobi的答案是正确的。
A lookahead could be added to his first version to insure a NOT just a dot or empty string. 可以在他的第一个版本中添加前瞻性,以确保不仅仅是点或空字符串。
^(?=.*\\d)\\d{0,3}(?:\\.\\d{0,2})?$
那这个呢?
/^\d{0,2}(?:\d\.|\.\d|\d\.\d)?\d?$/
You have to put the combination of decimal point and the decimal numbers optional. 您必须将小数点和十进制数字的组合设置为可选。 In your regex, only the decimal number is optional.
在您的正则表达式中,只有十进制数字是可选的。 1234 is accepted because 123 satisfy ^\\d{0,3}, not existing decimal point satisfy (.?), and 4 satisfy \\d{0,2}.
接受1234是因为123满足^ \\ d {0,3},不存在小数点满足(。?),而4满足\\ d {0,2}。
Kobi's answer provided you the corrected regex. Kobi的答案为您提供了更正的正则表达式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.