Reputation: 6896
I am trying to find a regex to limit what a person can use for a username on my site. I don't need to have it check to see how many characters there are in it, as another validation does this. Basically all I need to make it do is make sure that it allows: letters (capital and lowercase) numbers, dashes and underscores.
I came across this: /^[-a-z]+$/i
But it doesn't seem to allow numbers.
What am I missing?
Upvotes: 0
Views: 2333
Reputation: 17735
The regex you're looking for is
/\A[a-z0-9\-_]+\z/i
Meaning one or more characters of range a-z, range 0-9, - (needs to be escaped with a backslash) and _, case insensitive (the i qualifier)
Upvotes: 5
Reputation: 336148
Use
/\A[\w-]+\z$/
\w
is shorthand for letters, digits and underscore.
\A
matches at the start of the string, \z
matches at the end of the string. These tokens are called anchors, and Ruby is a bit special with regard to them: Most regex engines use ^
and $
as start/end-of-string anchors by default, whereas in Ruby they can also match at the start/end of lines (which matters if you're working with multiline strings). Therefore, it's safer (as @JustMichael pointed out) to use \A
and \z
because there is no such ambiguity.
Upvotes: 4
Reputation: 993075
Your regular expression contains a character class [-a-z]
that allows the characters -
(dash) and a
through z
. In order to expand the range of characters allowed by this character class, you will need to add more characters within the []
.
Please see Character Classes or Character Sets for further information and examples.
Upvotes: 3