re = /^(?=.{1,39}$)^[a-zA-Z\d]+(?:-[a-zA-Z\d]+)*$/m
str = '-username
_username_
__us_ername
us_er
username-
1user--name
132uname-
-uname1234
-username-
user--name
av34axc-
1234567890A1234567890B1234567890C1234567890D
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'
# Print the match result
str.scan(re) do |match|
puts match.to_s
end
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for Ruby, please visit: http://ruby-doc.org/core-2.2.0/Regexp.html