Aabishkar Wagle
Aabishkar Wagle

Reputation: 73

Regex for a string that must contain an uppercase letter, a lower case letter, a digit, a printable ASCI character with no white spaces

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

Answers (2)

Tim Biegeleisen
Tim Biegeleisen

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

knittl
knittl

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

Related Questions