1

The regex not working for "At least one Alphabets,At least one Digits and At least one Special Characters" and "At least one Digits and At least one Special Characters"

For example :

String passwordpattern="A9009"; //Not working for  pattern3

Note:It should check atleast one Alphabets, Digits and Special Characters

and

String passwordpattern="A3566523"; //Not working for  pattern4

Note:It should check at least one Special character and at least Digit

    //Alphabets, Digits and Special Characters
            String pattern3 = "[^\\\\w\\\\d]*(([0-9]+.*[A-Za-z]+.*[!#%&'()*+,-:;<=>?@}{]+.*)|[A-Za-z]+.*[0-9]+.*[!#%&'()*+,-:;<=>?@}{]+.*|[!#%&'()*+,-:;<=>?@}{]+.*[A-Za-z]+.*[0-9]+.*|[!#%&'()*+,-:;<=>?@}{]+.*[0-9]+.*[A-Za-z]+.*|[A-Za-z]+.*[!#%&'()*+,-:;<=>?@}{]+.*[0-9]+.*|[0-9]+.*[!#%&'()*+,-:;<=>?@}{]+.*[A-Za-z]+.*)";

   //Digits and Special Characters
  String pattern4 = "([^\\\\w\\\\d]*(([!#%&'()*+,-:;<=>?@}{]+.*[0-9]+.*)|[0-9]+.*([!#%&'()*+,-:;<=>?@]+.*)))";
2
  • 1
    Why not use separate checks for each requirement instead of trying to do everything in one regex. The purpose of the regexes is inherently unclear due to the opaque notation... Commented May 28, 2019 at 10:15
  • 1
    Neither of your passwords contains a special character. So of course they do not fulfill the "at least one special character" condition. Commented May 28, 2019 at 10:17

2 Answers 2

4

For these type of assertions it is better to use lookahead assertions.

"At least one Alphabets,At least one Digits and At least one Special Characters"

^(?=.*\pL)(?=.*\d)(?=.*\W).+$

\pL matches any unicode letter, \d matches any digit and \W any non-word character.

at least one Special character and at least Digit

^(?=.*\d)(?=.*\W).+$

Note that while using matches method there is no need to use anchors.

Sign up to request clarification or add additional context in comments.

3 Comments

@aubhava Can you give me regex for Atleast one Alphabets and Digits || Atleast one Alphabets and Special Characters
^(?=.*\pL)(?=.*\d).+$ for 1st and ^(?=.*\pL)(?=.*\W).+$ for second.
Thank you sir sharing nice code, could you please explain more on \pL, will be grateful to you sir.
0

This regex pattern will do what you want - match only if there is at least one alphabetic letter, one digit and one special character in a given string input:

^(?=.)[a-zA-Z]+[0-9]+[^\w]+[^\s]+

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.