I need a regular expression for my password format. It must ensure that password only contains letters a-z, digits 0-9 and special characters: .@#$%&.
I am using .NET C# programming language.
This is my code:
Regex userAndPassPattern = new Regex("^[a-z0-9.@#$%&]$");
if (!userAndPassPattern.IsMatch(username) || !userAndPassPattern.IsMatch(password))
return false;
The problem is that I always get back false.
!A || !Bis logically equivalent to!(A && B)So you could write better
Then you have a special character
$in you character class, maybe you need to mask it\$I’m not quite sure about this, because in a character class it is not a special character. Maybe it depends on the RegEx engine in use. If you mask the $ it should do no harm (
[a-z0-9.@#\$%&])Then you have just a single character to match. You need a quantifier
[a-z0-9.@#$%&]means one single character out of the given, will matchaorbor0but notab[a-z0-9.@#$%&]+many characters out of the given, from 1 to endless appearances, will matcha,b, andabandbaetc.edit
This is what you want