-4

Requirements:

• Usernames should be between 5 and 30 characters long
• They must contain letters and numbers.
• Usernames are not case sensitive.
• Spaces must not be used.

Allow: "!,@,#,$,%,^,?,_,~,-"

I've tried something like this for the length and normal characters requirements.

^[a-z0-9_-]{5,30}$  

This does not guarantee I get both letters and numbers - only that they are allowed

[A-Za-z].*[0-9]|[0-9].*[A-Za-z]  

I don't know how to limit this to 5-30 characters total?

Floris
  • 45,857
  • 6
  • 70
  • 122
euther
  • 2,556
  • 5
  • 24
  • 36
  • So how do you plan to use this regular expression? What are the details of the implementation - you want a "pass/fail" of some kind presumably? I am not sure why "usernames are not case sensitive" matters - are you saying "they must contain letters and numbers, but the case of the letters doesn't matter"? – Floris Oct 23 '13 at 20:23
  • take a look at http://stackoverflow.com/questions/7684815/regex-for-alpanumeric-with-at-least-1-number-and-1-character/7684859#7684859 for inspiration – Floris Oct 23 '13 at 20:53

2 Answers2

5

You can try this regex:

^(?=.*?[a-zA-Z])(?=.*?[0-9])[\w@#$%^?~-]{5,30}$

Live Demo & Examples: http://www.rubular.com/r/EXHHCoq0WC

Explanation:

  • ^ is line start
  • (?=.*?[a-zA-Z]) is a positive lookahead that will make sure there is atleast one alphabet
  • (?=.*?[0-9]) is a positive lookahead that will make sure there is atleast one digit
  • [\w@#$%^?~-]{5,30} is using character class for 5 to 30 characters specified inside square brackets
  • $ is line end

Lookaround Reference: www.regular-expressions.info/lookaround.html

anubhava
  • 761,203
  • 64
  • 569
  • 643
1

Here are some hints:

[:alpha:] is a "special character" that is "any upper or lower case letter"

[:digit:] is "any digit"

[!@#$%^?_~-] means "match any of these characters"

[^ ] means "don't match a space"

{5,30} means "match the preceding expression between 5 and 30 times

Regex allows for things like | between two expressions to match "either this or that".

http://rubular.com/ is a great "regex sandbox" - you can enter expressions, and see what matches

When you have played around with the above for a while and got it "almost working", there will be people here to help you "get across the finish line".

Floris
  • 45,857
  • 6
  • 70
  • 122
  • this is great information, I'll definitely to look into it. Thanks for the advice as well, I did research a lot but I didn't have the time to show you guys my whole investigation, I'll make sure to fill my questions with more information. Have a good day. – euther Oct 23 '13 at 21:24
  • 1
    Better questions get better answers. You are getting some very experienced brain power for free - you show respect by making the best question you can... It is a learning journey for all of us. I made a couple of small edits to your question to show simple ways to improve it. – Floris Oct 23 '13 at 22:35