0

I need help creating the regex for a password.

The password can contain letters, numbers, underscores ( _ ), dollar signs ( $ ) and hyphens ( - ), must be at least 3 characters long and at most 30 characters long.

4
  • 2
    If you find yourself asking a multiple questions about a specific topic, it might be worth investing some time to learn the basics so you can solve the trivial tasks yourself. There are many tutorials around for regexes, e.g. regex.learncodethehardway.org Commented May 5, 2012 at 7:04
  • You may find this useful regexbuddy.com/create.html Commented May 5, 2012 at 7:07
  • 1
    That's quite a restrictive collection of characters. Why are you forcing people to make passwords less secure by outlawing lots of common characters (such as % and ^)? Commented May 5, 2012 at 7:12
  • This is actually for a username, Shouldn't have put password there... Whoops Commented May 5, 2012 at 7:19

2 Answers 2

2

Letters, numbers, underscores, dollar signs and hyphens are covered by this:

[a-zA-Z0-9_$-]

Limiting it to 3 to 30 is covered by this:

{3,30}

In the end, we can reduce it a bit by adding the case-insensitive modifier:

/^[a-z0-9_$-]{3,30}$/i

Adding the ^ and $ force it to match from start to finish, meaning we won't be matching a subset of the tested string. Either the entire submitted string passes, or fails.

You can try it out against a few password by visiting http://regexr.com?30ru6

Sign up to request clarification or add additional context in comments.

1 Comment

@keto23 My pleasure. Remember to study the solution, ask questions, and learn from these answers.
2
/[a-z0-9_$-]{3,30}/

Will match according to your requirements.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.