This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Password Regex Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Password Regex" Watch "Password Regex" New topic
Author

Password Regex

Scott McGhee
Greenhorn

Joined: Apr 10, 2007
Posts: 22
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
internet detective
Marshal

Joined: May 26, 2003
Posts: 30068
    
149

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.


[Blog] [JavaRanch FAQ] [How To Ask Questions The Smart Way] [Book Promos]
Blogging on Certs: SCEA Part 1, Part 2 & 3, Core Spring 3, OCAJP, OCPJP beta, TOGAF part 1 and part 2
Mike Simmons
Ranch Hand

Joined: Mar 05, 2008
Posts: 2982
    
    9
You can use lookahead or lookbehind operators to look ahead without advancing. Lookahead is probably a little simpler:
Scott McGhee
Greenhorn

Joined: Apr 10, 2007
Posts: 22
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
internet detective
Marshal

Joined: May 26, 2003
Posts: 30068
    
149

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.
 
subject: Password Regex
 
Similar Threads
regex for nameFields: first & last names tested separately
RegExp Help Needed!
Regular expressions
How to make a regular expression that the order doesn't matter
regular expression doubt