I'm writing a simple android app for saving your favorite games in a list.
In the first screen a user has to enter his gamertag
(as a String
). The gamertag should only contain letters
from a-z (uppercase and lowercase)
, numbers (0-9)
and underscores/hpyhens (_ and -)
.
I can get it to work with an underscore
in every position or a hyphen
at the beginning. But if the String
contains a hyphen
in the middle it gets "split
" into two pieces and if the hyphen
is at the end, it stands alone.
I came up with this regex
:
[a-zA-Z0-9_\-]\w+
in java it looks a little different because the \ needs to be escaped:
[a-zA-Z0-9_\\-]\\w+
Gamertags
that should validate:
- GamerTag
- Gamer_Tag
- _GamerTag
- GamerTag_
- -GamerTag
- Gamer-Tag
- GamerTag-
Gamertags
that shouldn't validate:
- !GamerTag
- Gamer%Tag
- Gamer Tag
Gamertags
that should validate, but my regex
fails:
- Gamer-Tag
- GamerTag-
Your pattern [a-zA-Z0-9_\-]\w+
matches 1 character out of the character class followed by 1+ times a word character \w
which does not match a -
.
You could repeat the character class 1+ times where the hyphen is present and if the hyphen is at the end of the character class you don't have to eacape it.
[a-zA-Z0-9_-]+
The Gamer-Tag
does not get split but has 2 matches. The character class matches G
and the \w+
matches amer
. Then in the next match the character class matches -
and \w+
matches Tag
.
If those are the only values allowed, you could use anchors ^
to assert the start and $
to assert the end of the string.
^[a-zA-Z0-9_-]+$