Reputation: 73
Help me write a JavaScript regex for a string that can contain:
Example:
"NewYork12@" can be a valid string. "New York12@" is an invalid string.
What I tried:
/(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[A-Za-z\d](?=.*[!-~])/
This is not working as it accepts whitespace as well.
Thanks.
Upvotes: 1
Views: 983
Reputation: 522161
I would just use \S+
as the actual pattern to be matched here, keeping your positive lookaheads in place:
/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)\S+$/
This pattern says to:
^ from the start of the input
(?=.*[a-z]) assert lowercase letter present
(?=.*[A-Z]) assert uppercase letter present
(?=.*\d) assert digit present
\S+ then match one or more exclusively non whitespace characters
$ end of the input
Upvotes: 1
Reputation: 265585
Negative matches can be very difficult to properly express in a regular expression. It is often simpler to not express everything as a single regex. Use multiple regular expressions and combine their result in the host language:
if (
input.match(/[A-Z]/) // at least 1 upper case letter
&& input.match(/[a-z]/) // at least 1 lower case letter
&& input.match(/[0-9]/) // at least 1 digit
&& !input.match(/\s/) // no whitespace
) {
// all rules fulfilled
}
Upvotes: 0