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