This week's book giveaways are in the Refactoring and Agile forums.
We're giving away four copies each of Re-engineering Legacy Software and Docker in Action and have the authors on-line!
See this thread and this one for details.
Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Password Regex

 
Scott McGhee
Greenhorn
Posts: 22
  • 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: 34095
337
Eclipse IDE Java VI Editor
  • 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
  • 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
  • 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: 34095
337
Eclipse IDE Java VI Editor
  • 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!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic