tags:

views:

120

answers:

2

I want the username to be any characters with _ or - in it but this in Perl is not working, why is it?

if ("kunjaaN-" =~ /^[a-zA-Z-_]{1,7}$/)
{ print "equal" ; }
+10  A: 

It's not working because kunjaaN- is eight characters, and you're limiting yourself to 1..7

For a username, why not increase the limit to something decent?

Also, if you want _ included you need to include that in your character class.

Try this regex:

^[a-zA-Z_-]{1,16}\z


Note:
Inside character classes, the - character can have special meaning. For example, [a-z] means 'the range of characters starting with a and ending in z', whilst [az-] means 'either a or z or -'.

To make a - non-special you can place it at the start or end of a class, or escape it with a backslash. [a\-z] will match a or z or -.
Escaping is generally preferred since it avoids accidents if extra characters are inadvertently added to the end of the class.

Peter Boughton
This is embarrasing. Thanks.
kunjaan
Heh, we all do things like this from time to time. :)
Peter Boughton
Yes, but not all of us have asked what the underscore does in a regular expression ;-)
innaM
You make the change but don't point it out, about the problems with the question's character class. The original version didn't include match on -. The reason for this is that - is treated as a range operator unless it is the frist or last character.
EmFi
EmFi, pay attention to edit times - the question was modified after I answered. Since the question has now changed, I'll go add information about when `-` is special or not.
Peter Boughton
+4  A: 

If you don't want to allow a possible newline at the end of your string, use the \z end of string anchor instead of the $ anchor:

 /^[a-z_-]{1,8}\z/i
brian d foy
Thanks for the tip.
kunjaan