Reputation: 951
I need only specific number of special characters in a password. I tried the following regex
(?=.*[$@!%*?&]{1})
It takes special character from that set but accepts even multiple special characters.
{1} means number of characters from the set I am allowing the string to validate.
For example,
Alpha1?
should be true for the above regular expression
@lpha1?
should not be validated by above regex because now it has 2 characters from that set.
Can someone please help? Any help is appreciated. Thanks in advance
Upvotes: 0
Views: 1244
Reputation: 10360
Try this Regex:
^[^$@!%*?&\n]*[$@!%*?&][^$@!%*?&\n]*$
Explanation:
^
- asserts the start of the string[^$@!%*?&\n]*
- matches 0+ occurrences of any character that does NOT fall in these set of characters: $
, @
, !
, %
, ?
, &
or a newline character[$@!%*?&]
- matches one occurrence of one of these characters: $
, @
, !
, %
, ?
, &
[^$@!%*?&\n]*
- matches 0+ occurrences of any character that does NOT fall in these set of characters: $
, @
, !
, %
, ?
, &
or a newline character$
- asserts the end of the stringJAVA Code:(Generated here)
import java.util.regex.Matcher;
import java.util.regex.Pattern;
final String regex = "^[^$@!%*?&\\n]*[$@!%*?&][^$@!%*?&\\n]*$";
final String string = "abc12312\n"
+ "$123\n"
+ "$123?\n"
+ "Alpha1?\n"
+ "@lpha1?";
final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(string);
while (matcher.find()) {
System.out.println("Full match: " + matcher.group(0));
for (int i = 1; i <= matcher.groupCount(); i++) {
System.out.println("Group " + i + ": " + matcher.group(i));
}
}
Update:
To get the strings with exactly 2 special characters, use this:
^(?:[^$@!%*?&\n]*[$@!%*?&]){2}[^$@!%*?&\n]*$
To get strings with exactly 5 spl. characters, replace {2} with {5}.
To get string with 2-5 special characters, use {2-5}
Upvotes: 2
Reputation: 491
In Java you can use the method replaceAll
to filter all characters up to your set of special characters. The method takes as argument a regular expression. The size of the result represents the count of special characters:
String password = "@foo!";
int size = password.replaceAll("[^$@$!%*?&]","").length();
System.out.println(size);
// will print 2
Upvotes: 1