Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this questionI 开发者_StackOverflow社区would like to validate the user input field to only allow user to input +1,-1,+10,-10 and +25,-25, nothing else. What is the regular expression for this restriction?
Try with:
/^[-+](1|10|25)$/
It will allow one of your 6 possibilities.
I wouldn't bother with a regexp. Presumably, you're going to ultimately need to parse the number from a String to an int, yes? In which case you could just immediately parse it and check the outcome is as expected, although this won't enforce the "+" sign if that's mandatory - but manually checking for the sign before parsing would be simple.
If you're absolutely allowing only the specified inputs, and nothing else, then the following regex will do it:
/^[-+](1|10|25)$/
But what if someone enters "10" -- ie "+10", but without the plus sign? Is that allowed or not? You haven't specified. If it is, then the +/- needs to be optional, so the regex changes to this:
/^[-+]?(1|10|25)$/
Note that this regex also has start and end anchors (ie ^
and $
), meaning that it won't allow any other characters in the string. Without them, it could match a string that contained "+20" in amongst other text.
You don't specify a language the regex should be in, but this should work:
[+-][12][05]?
精彩评论