Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regular expression for some specific number [closed]

Tags:

regex

I 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?

like image 347
Mellon Avatar asked Apr 05 '11 11:04

Mellon


3 Answers

Try with:

/^[-+](1|10|25)$/

It will allow one of your 6 possibilities.

like image 99
hsz Avatar answered Nov 09 '22 14:11

hsz


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.

like image 23
dty Avatar answered Nov 09 '22 12:11

dty


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.

like image 37
Spudley Avatar answered Nov 09 '22 12:11

Spudley