开发者

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.

I want it to match: 12, 123, 123.5, 123.55, 123. I do not want it to match: abc, 1234, 123.555

What I have so far it: ^\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.

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:

  • Escaping the dot, or it matches any character (except new lines), including more digits.
  • Made the whole decimal part optional, including the dot. That is - the decimal dot is not optional - it must be including if we are to match any digit from the decimal part.
  • Even if you have escaped the dot, ^\d{0,3}(\.?)\d{0,2}$ isn't correct. With the dot optional, it can match 12378: \d{0,3} matches 123, (\.?) doesn't match anything, and \d{0,2} matches 78.

Working example: http://rubular.com/r/OOw6Ucgdgq


What about this?

/^\d{0,2}(?:\d\.|\.\d|\d\.\d)?\d?$/


Maybe this (untested)

^(?=.*\d)\d{0,3}\.?(?<=\.)\d{0,2}$

Edit - the above is wrong.

@Kobi's answer is correct.

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})?$


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

Kobi's answer provided you the corrected regex.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜