Lajos Arpad Lajos Arpad - 2 months ago 27
Java Question

How to check whether a string contains lowercase letter, uppercase letter, special character and digit?

I've been Googling a lot and I didn't find an answer for my question:

How can I check with a regular expression whether a string contains at least one of each of these:

  • Uppercase letter

  • Lowercase letter

  • Digit

  • Special Character:

So I need at least a capital letter and at least a small letter and at least a digit and at least a special character.

I'm sure the answer is very simple, but I can't find it. Any help is greatly appreciated.


This does what you want in java as a single regex, although I would personally use something like the solution provided by Mark Rhodes. This will get ridiculous quick (if it isn't already...) as the rules get more complicated.

String regex = "^(?=.*?\\p{Lu})(?=.*?[\\p{L}&&[^\\p{Lu}]])(?=.*?\\d)" + 
  1. ^ This matches the beginning of the string. It's not strictly necessary for this to work, but I find it helps readability and understanding. Also, using it when you can often makes a big performance improvement and is almost never a penalty.

  2. (?=X) This is called a positive lookahead. Basically what we're saying is "The beginning of the string (^) must be followed by this thing X in order for a match, but DO NOT advance the cursor to the end of X, stay at the beginning of the line. (that's the "look ahead" part.)

  3. .*?\p{Lu} eat characters after the beginning of the line until you find a capital letter. This will fail to match if no capital letter is found. We use \p{Lu} instead of A-Z because we don't want people from other parts of the world to throw up their hands and complain about how our software was written by an ignorant American.

  4. Now we go back to the beginning of the line (we go back because we used lookahead) and start a search for .*?[\p{L}&&[^\p{Lu}]] shorthand for "all letters, minus the capitals" (hence matches lower case).

  5. .*?\d + .*?[`~!@#$%^&*()\-_=+\\\|\[{\]};:'\",<.>/?] repeat for digits and for your list of special characters.

  6. .*$ Match everything else until the end of the line. We do this just because of the semantics of the 'matches' methods in java that see if the entire string is a match for the regex. You could leave this part of and use the Matcher#find() method and get the same result.

  7. The Owl is one of the best books ever written on any technical subject. And it's short and fast to read. I cannot recommend it enough.