Reputation: 1274
Please give me the code in regex for password validation in java which should consist of one Caps character,one integer ,one following symbols( @,#,$,%,^,&,+,=) and small characters.
I have been trying this with different separate regular expressions and one combined regular expression.
Actually i am already having a single regex that evaluates all the conditions in javascript.
I am not able to use it in Java back end. I tried by escaping \
. Its also not working.
Here is my code:
Pattern pattern = Pattern.compile("/.*(?=.{6,})(?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=]).*$/");
Matcher matcher = pattern.matcher("Aa@1");
if(matcher.matches()){
System.out.println("Matched");
}
else{
System.out.println("No mat");
}
The original javascript regex is
/.*(?=.{6,})(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=]).*$/
In that the \d
gave me error due to the escaping character. So, i added another \
before that in the Java Version.
I am not able to understand what is going wrong.
Thanks in Advance.
Upvotes: 1
Views: 462
Reputation: 523214
You don't need the /
's in Java. It will actually match a slash. Also, the leading .*
is useless (although it won't affect the result).
Pattern pattern = Pattern.compile("(?=.{6,})(?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=]).*$");
Upvotes: 1
Reputation: 336108
You were nearly there, but you missed a few details:
First, the starting point is bad - that JavaScript regex is ugly. Instead of
/.*(?=.{6,})(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=]).*$/
use this:
/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=]).{6,}$/
Then, to translate the regex to Java, you need to remove the delimiters (and use quotes instead, not additionally like you did) and double the backslashes (like you already did):
Pattern pattern = Pattern.compile("^(?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=]).{6,}$");
Now it should work.
Upvotes: 4