0

I need a regex that contains at least 1 uppercase, lowercase, numbers, 8 characters special character, and DOES NOT CONTAIN WHITESPACE.

I'm not able to add the white space condition:

/^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[^a-zA-Z0-9\s]).{8,}$/

This \s, I thought that would validate the white space, but it's not working...

Thank you

Gustavo Rey
  • 115
  • 9
  • 1
    `.` matches spaces and tabs, so don't use that in the last part of your pattern. What's the full range of characters that you want to allow? Anything other than whitespace? – CAustin Jul 28 '23 at 22:11
  • 2
    Does this answer your question? [Regex for password must contain at least eight characters, at least one number and both lower and uppercase letters and special characters](https://stackoverflow.com/questions/19605150/regex-for-password-must-contain-at-least-eight-characters-at-least-one-number-a) – maraaaaaaaa Jul 28 '23 at 22:17

1 Answers1

1

To match a string that contains at least one uppercase letter, one lowercase letter, one number, one special character, is at least 8 characters long, and does not contain any whitespace, you could use a regex pattern with lookaheads to verify each of these requirements. Here's how it could look:

regex: ^(?=.*[A-Z])(?=.*[a-z])(?=.*\d)(?=.*[\W])(?!.*\s).{8,}$

Here's how it works:

^ asserts the start of the string.

(?=.*[A-Z]) requires at least one uppercase letter.

(?=.*[a-z]) requires at least one lowercase letter.

(?=.*\d) requires at least one number.

(?=.*[\W]) requires at least one non-word character (special characters).

(?!.*\s) asserts that no whitespace characters are allowed.

.{8,} requires at least 8 characters in total.

$ asserts the end of the string.

The .* inside the lookaheads (?=...) and (?!...) allows for any characters (or no characters at all) to appear before the required or disallowed characters. The . matches any character except for a newline, and the * quantifier allows this to be repeated any number of times, including zero times.

Remember, regular expressions can vary between programming languages and environments, so you may need to adjust this for your specific use case. This regular expression pattern should work in most common languages and environments, like JavaScript, Python, Java, and more.

Ilan Rosenbaum
  • 138
  • 1
  • 7