neca
neca

Reputation: 139

Writing regular expression that will filter entered username

I want to write a regexp that will filter any username which:

The closest I've come to my result is something like this:

^[a-zA-Z\d](?:[a-zA-Z\d]|-(?=[a-zA-Z\d])){0,38}

This matches exactly what it should match, but it also matches some things that it shouldn't.

Basically these shouldn't be valid:

-username
_username_
__us_ername
us_er
username-
1user--name
132uname-
-uname1234
-username-
user--name
av34axc-
1234567890A1234567890B1234567890C1234567890D

And these should be valid:

Username
a-a
aBc
BaC
1-1
1-2-3-4
q-1-2-3
q-q-q-q-q
username
123username123
username3123
1234
user-name
13-13
q1-q2-q3
a
A
1234567890A1234567890B1234567890C123456
1234567890A123456-7890B1234567890C12345

Upvotes: 5

Views: 711

Answers (2)

trincot
trincot

Reputation: 350167

You could use negative look ahead to implement the hyphen restrictions:

^(?!.*-(-|$)|-)[a-z\d-]{1,39}$

Upvotes: 0

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626758

You may use

^(?=.{1,39}$)[a-zA-Z\d]+(?:-[a-zA-Z\d]+)*$

See the regex demo and the Regulex graph:

enter image description here

Details

  • ^ - start of string
  • (?=.{1,39}$) - the length must be 1 to 39 chars
  • [a-zA-Z\d]+ - 1+ alphanumeric chars
  • (?:-[a-zA-Z\d]+)* - 0 or more repetitions of
    • - - a hyphen
    • [a-zA-Z\d]+ - 1+ alphanumeric chars
  • $ - end of string.

Upvotes: 3

Related Questions