You just need to add underscore _
and hyphen -
to your first and last character set to allow your username to start or end with those two new characters and write your regex like this,
^[A-Za-z0-9_-]+[A-Za-z0-9_.]*[A-Za-z0-9_-]+$
and as \w
is same as writing [a-zA-Z0-9_]
hence you can compact your regex to this,
^[\w-]+[\w.]*[\w-]+$
Just want to also mention one point that whenever you write a hyphen -
in a character set, make sure to always place it as either the first or last character in the character set, else unknowingly, the hyphen may act either as a range specifier and may not act as a literal hyphen. Although as in above regex, there is only \w
and -
in the character set, hence we don't need to worry here about the placement of hyphen.
Regex Demo
Also, I am not sure if you want to allow usernames (unlike a variable name which generally is allowed to be just one character) of just one character, but if you do, then you can modify your regex to this,
^[\w-]+([\w.]*[\w-]+)?$
Regex Demo allowing just one character as username