tags:

views:

89

answers:

4

Can someone give me a regular expression for a number to be between 1 and 5, single digit

e.g. input has to be a number between 1 and 5 , 55 or 23 would not match

+7  A: 

Try using anchors:

/^[1-5]$/

Explanation:

^     Start of line/string.
[1-5] A digit between 1 and 5.
$     End of line/string.
Mark Byers
A: 

Maybe this should do [1-5]

Faisal Feroz
No it wouldn't, since it would match 12345 or 5555 or this5is_not_a_number.
Paul Tomblin
@Paul: No, it would match the 1, 2, 3, 4 and 5 in 12345.
splash
This is a valid answer, I don't see why the downvote...
veljkoz
@splash, that's the problem - if you fed it '12345' or 'this5is_not_a_number', it would say it matched, because it matched one part of the string. If you want to make it exclusive, as the original question asked, then you need anchors like @Mark Byers said.
Paul Tomblin
@Paul, you are right in context of the original question, but your phrasing `it would match 12345` is imprecise as to @Faisal's regular expression `[1-5]`. ;-)
splash
@splash, excuse me for thinking that an answer to the question should answer "in the context of the original question".
Paul Tomblin
+1  A: 

Would it not be simpler to check it as a number (ie if(x>=1 && x<=5) or something similar) rather than using a regex?

Spudley
@Spudley - it depends on whether the programming language converts strings to numbers automatically, or requires you to call methods and deal with exceptions in order to do this.
Stephen C
A: 

Much more concise to say

if(x> 0 and x<5)

IMHO

Visage
Right, if `between` means exclusive 1 and 5.
splash
@splash: No, this includes 1 but excludes 5.
Mark Byers
@Mark, you are right. How blind of me!
splash