Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 281
Lajos Arpad Avatar asked Jan 09 '12 20:01

Lajos Arpad


People also ask

How do you know if a string is uppercase or lowercase?

To check if a letter in a string is uppercase or lowercase use the toUpperCase() method to convert the letter to uppercase and compare it to itself. If the comparison returns true , then the letter is uppercase, otherwise it's lowercase. Copied!

How do you check for special characters in a string?

To check if a string contains special characters, call the test() method on a regular expression that matches any special character. The test method will return true if the string contains at least 1 special character and false otherwise.

How do you check if a string contains uppercase and lowercase and number in Java?

The java. lang. Character. isUpperCase(char ch) determines if the specified character is an uppercase character.


1 Answers

Regular expressions aren't very good for tests where you require all of several conditions to be met.

The simplest answer therefore is not to try and test them all at the same time, but just to try each of the four classes in turn.

Your code might be fractionally slower, but it'll be easier to read and maintain, e.g.

public boolean isLegalPassword(String pass) {       if (!pass.matches(".*[A-Z].*")) return false;       if (!pass.matches(".*[a-z].*")) return false;       if (!pass.matches(".*\\d.*")) return false;       if (!pass.matches(".*[~!.......].*")) return false;       return true; } 

EDIT fixed quote marks - been doing too much damned JS programming...

like image 157
Alnitak Avatar answered Sep 22 '22 09:09

Alnitak