-1

im trying to validate passwords on my servlet using the following requirments

o The password must consist of one number and one of the following
special characters: !@#$%^&*()

Note: 1! and !1 are both valid passwords

the regex ive been trying to get to work is

?=.*[a-zA-Z])(?=.*\\d)(?=.*[!@#$%&*()_+=|<>?{}\\[\\]~-])

but it does not take 1! or !1

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
user3225981
  • 107
  • 7

1 Answers1

0

And why not "simple" like this,

/^((?:\d[!@#$%^&*()])|(?:[!@#$%^&*()]\d))$/

[!@#$%^&*()] special characters
\d one digit
(?: ...) don't capture the group
| "Or" operator ^ (String) Beginning $ (String) End

if only one of these special characters and only one number should match.

mini Javascript Demo:

var items = ["!1","1!","123123","123!","1!2@3"]

for (var idx in items){
  var item = items[idx];
  document.write(item +" => "+ (item.match(/^((?:\d[!@#$%^&*()]){1}|(?:[!@#$%^&*()]\d))$/)||"nomatch"));
  document.write("<br />");
}
winner_joiner
  • 12,173
  • 4
  • 36
  • 61