File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Soft Skills: The software developer's life manual this week in the Jobs Discussion forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Password Regex

 
Scott McGhee
Greenhorn
Posts: 22
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm struggling to figure out a single regular expression which will match a password having the following rules:

o Passwords must be 6-16 characters.
o Allowed characters are alphanumeric, hyphen(-) and underscore(_)
o They must contain both numbers and letters

Currently the code uses 3 regular expressions to accomplish the goal:


And then to check the password:



What is the easiest way to construct a single regular expression combining these 3?
 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 33667
316
Eclipse IDE Java VI Editor
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Scott,
The easiest thing to do is leave them separate. I can't think of any way to check all three of these things. Note your requirements say the max length is 16 and your reg exp is 24. I assume one is a typo, but I figured I would mention it.
 
Mike Simmons
Ranch Hand
Posts: 3028
10
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can use lookahead or lookbehind operators to look ahead without advancing. Lookahead is probably a little simpler:
 
Scott McGhee
Greenhorn
Posts: 22
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you Mike, that clears it up for me. The lookahead seems to be working, I tested on a few input strings and it looks good.

Also thanks Jeanne for pointing out the typo.
 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 33667
316
Eclipse IDE Java VI Editor
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Mike,
Interesting! I was puzzled by doing the look ahead for two things. Double lookahead is a good technique to remember!
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic